1、GCD方式创建单例
static id _instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
_instance =[superallocWithZone:zone];
});
return_instance;
}
+(instancetype)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
_instance =[[self alloc]init];
});
return_instance;
}
-(id)copyWithZone:(NSZone *)zone
{
return_instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone {
return_instance;
}
2、互斥锁方式
static id _instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self){
if(_instance == nil){
_instance =[superallocWithZone:zone];
}
}
return_instance;
}
+(instancetype)sharedInstance
{
@synchronized(self){
if(_instance == nil){
_instance =[[self alloc]init];
}
}
return_instance;
}
-(id)copyWithZone:(NSZone *)zone
{
return_instance;
}
网友评论