iOS 单例写法
程序员文章站
2022-07-13 23:46:16
...
static SLShare *_instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
});
return _instance;
}
// 为了使实例易于外界访问 我们一般提供一个类方法
// 类方法命名规范 share类名|default类名|类名
+(instancetype)shareTools {
return [[self alloc] init];
}
// 为了严谨,也要重写copyWithZone 和 mutableCopyWithZone
-(id)copyWithZone:(NSZone *)zone {
return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone {
return _instance;
}
上一篇: IOS单例的写法
下一篇: iOS 再谈单例的几种写法