싱글턴(Singleton)
해법
+(MyClass *)sharedMyClass {
static dispatch_once_t once;
static MyClass *shared = nil;
dispatch_once(&once, ^{
shared = [[MyClass alloc] init];
});
return shared;
}
다른 해법(느림)
+(MyClass *)sharedMyClass {
static MyClass *shared = nil;
@synchronized (self) {
if (shared==nil) {
shared = [[MyClass alloc] init];
}
return shared;
}
}
잘못된 해법(스레드 안전이 아님)
+(MyClass *)sharedMyClass {
static MyClass *shared = nil;
if (shared==nil) {
shared = [[MyClass alloc] init];
}
return shared;
}