//gcd创建单例:
static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [superallocWithZone:zone];
});
return_instance;
}//保证oncetoken只被执行一次
+ (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;
}
//互斥锁
static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if(_instance == nil) {
_instance = [superallocWithZone:zone];
}//保证self对象不被其他进程修改 起到线程保护作用 同时括号内的代码块 会被加锁 其他线程访问会休眠 直到代码块执行结束或者抛出异常
}
return_instance;
}
+ (instancetype)sharedInstance
{
@synchronized(self) {
if(_instance == nil) {
_instance = [[self alloc] init];
}
}
return_instance;
}
- (id)copyWithZone:(NSZone *)zone
{
return_instance;
}
网友评论