iOS单例写法
程序员文章站
2022-07-14 07:51:59
...
写法1:
实现文件:GCD
@implementation NewObject
static NewObject *_instance = nil;
+ (instancetype)shareInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[super allocWithZone:NULL] init];
});
return _instance;
}
+ (id)allocWithZone:(struct _NSZone *)zone {
return [NewObject shareInstance];
}
- (id)copyWithZone:(struct _NSZone *)zone {
return [NewObject shareInstance];
}
- (id)mutableCopyWithZone:(struct _NSZone *)zone {
return [NewObject shareInstance];
}
@end
写法2:
static A *_instance;
@implementation A
+ (instancetype)shared {
@synchronized(self) {
if (!_instance) {
_instance = [[super allocWithZone: NULL] init];
}
}
return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
return [A shared];
}
- (id)copyWithZone:(struct _NSZone *)zone {
return [A shared];
}
- (id)mutableCopyWithZone:(struct _NSZone *)zone {
return [A shared];
}
@end
下一篇: 《从零开始做运营》读书笔记