iOS开发 单例
作者:
Hao_Orz | 来源:发表于
2018-04-18 11:03 被阅读0次#import "Tools.h"
@implementation Tools
// 创建静态对象 防止外部访问
static Tools *_tool;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_tool == nil) {
_tool = [super allocWithZone:zone];
}
});
return _tool;
}
// 为了使实例易于外界访问 我们一般提供一个类方法
// 类方法命名规范 share类名|default类名|类名
+ (instancetype)shareTools {
// 最好用self 用Tools他的子类调用时会出现错误
return [[self alloc]init];
}
// 为了严谨,也要重写copyWithZone 和 mutableCopyWithZone
- (id)copyWithZone:(NSZone *)zone {
return _tool;
}
- (id)mutableCopyWithZone:(NSZone *)zone {
return _tool;
}
本文标题:iOS开发 单例
本文链接:https://www.haomeiwen.com/subject/rxkvkftx.html
网友评论