iOS 线程安全的单例
20 Sep 2015
+ (instancetype)sharedStore {
static OBJ *sharedObj = nil;
// Not thread safe
/*if (!sharedStore) {
sharedStore = [[self alloc]initPrivate];
}*/
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedObj = [[self alloc] initPrivate];
});
return sharedStore;
}
- (instancetype)initPrivate {
self = [super init];
if (self) {
//do some initialize
}
return self;
}
- (instancetype) init {
@throw [NSException exceptionWithName:@"Singleton" reason:@"PLS use +[OBJ sharedObj]" userInfo:nil];
return nil;
}