//利用dispatch_once來寫,會比@synchronized(self)快上三倍,但如果instance被消除,前言不會重新init一次,但外部本來就無法消除內部的instance,所以小心不要在內部消除即可
//自己的範例
#pragma mark - Initial with Singleton
+(instancetype) sharedInstance {
static dispatch_once_t pred;
static CBManager *instance = nil;
dispatch_once(&pred, ^{instance = [[self alloc] initSingleton];});
return instance;
}
- (id)init {
return nil;
}
- (id)initSingleton {
self = [super init];
if ( self ) {
//TODO: ...
}
return self;
}
//網路上的範例
+ (MYSingleton *)sharedSingleton {
static dispatch_once_t pred;
static MYSingleton *instance = nil;
dispatch_once(&pred, ^{instance = [[self alloc] initSingleton];});
return instance;
}
- (id)init {
// Forbid calls to –init or +new
NSAssert(NO, @”Cannot create instance of Singleton”);
// You can return nil or [self initSingleton] here,
// depending on how you prefer to fail.
return nil;
}
// Real (private) init method
- (id)initSingleton {
self = [super init];
if ((self = [super init])) {
// Init code }
return self;
}
沒有留言:
張貼留言