1利用GCD方式实现单例(ARC)
#import "People.h" @implementation People
static id _instace;
+(id)allocWithZone:(struct _NSZone *)zone{ //为防止用alloc创建对象 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace=[super allocWithZone:zone]; }); return _instace; } +(id)shareInstace{ if (_instace==nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ //dispatch_once 里的代码块只会执行一次 _instace=[[self alloc]init]; }); } return self; } -(id)copyWithZone:(NSZone*)zone{ //为防止用alloc创建对象 return _instace; } @end
2利用GCD方式实现单例(非ARC)
@implementation People static id _instace; + (id)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super allocWithZone:zone]; }); return _instace; } + (instancetype)sharedDataTool { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [[self alloc] init]; }); return _instace; } - (id)copyWithZone:(NSZone *)zone { return _instace; } - (oneway void)release { } - (id)retain { return self; } - (NSUInteger)retainCount { return 1; } - (id)autorelease { return self; } @end
原文:http://www.cnblogs.com/mgy007/p/4564931.html