Objective-C 单例模式

//Creating a Singleton Instance
static
MyGizmoClass *sharedGizmoManager = nil; + (MyGizmoClass*)sharedManager { if (sharedGizmoManager == nil) { sharedGizmoManager = [[super allocWithZone:NULL] init]; } return sharedGizmoManager; } + (id)allocWithZone:(NSZone *)zone { return [[self sharedManager] retain]; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (NSUInteger)retainCount { return NSUIntegerMax; //denotes an object that cannot be released } - (void)release { //do nothing } - (id)autorelease { return self; }

 

再来个现代版本的代码 ,这种实现利用了GCD(Grand Central Dispatch)和ARC(Automatic Reference Counting)
//ARC开启
+ (id)sharedInstance { static dispatch_once_t pred = 0; __strong static id _sharedObject = nil; dispatch_once(&pred, ^{ _sharedObject = [[self alloc] init]; // or some other init method }); return _sharedObject; }

 

 

posted @ 2013-04-26 09:43  酱酱爱  阅读(241)  评论(0编辑  收藏  举报