iOS创建单例的方式有很多,系统中的如:
[NSUserDefaults standardUserDefaults];
[NSFileManager defaultManager];
等等这些方式创建单例。但是这些不是绝对的单例,如果用下面方式创建
他们就不是一个对象了。
[NSUserDefaults new];
[NSFileManager new];
所以创建绝对的单例,就是无论使用何种方式调用,只生成一个对象。
我们就要多重写几个方法,具体操作如下:
#pragma mark -- 创建绝对的单例
static DownloadManager *_shareInstance;
// 绝对的单例: 无论通过什么样的方式创建,都是一个对象
+ (instancetype)shareInstance {
if (!_shareInstance) {
_shareInstance = [[WHYDownloadManager alloc] init];
}
return _shareInstance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
if (!_shareInstance) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_shareInstance = [super allocWithZone:zone];
});
}
return _shareInstance;
}
- (id)copyWithZone:(NSZone *)zone {
return _shareInstance;
}
- (id)mutableCopyWithZone:(NSZone *)zone {
return _shareInstance;
}
对于copy,mutableCopy方法,我们要遵循<NSCopying, NSMutableCopying>协议
<NSCopying, NSMutableCopying>