static TRDataManager *_dataManagerByUnsafe = nil;
+ (instancetype)sharedDataManagerByUnsafe {
if (!_dataManagerByUnsafe) {
_dataManagerByUnsafe = [[TRDataManager alloc] init];
}
return _dataManagerByUnsafe;
}
////////////////////////////////////
static TRDataManager *_dataManagerBySafe = nil;
+ (instancetype)sharedDataManagerBySafe {
//1.创建一个静态的一次性任务对象
static dispatch_once_t onceToken;
//2.调用一次性任务方法
dispatch_once(&onceToken, ^{
//创建单例对象
_dataManagerBySafe = [[TRDataManager alloc] init];
});
//3.返回单例对象
return _dataManagerBySafe;
}
//重写alloc方法; 或者重写allocWithZone
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_dataManagerBySafe = [super allocWithZone:zone];
});
return _dataManagerBySafe;
}
//当copy当前类型对象时候,返回唯一的单例对象
- (id)copyWithZone:(NSZone *)zone {
return _dataManagerBySafe;
}
//////////////////////////////
//创建单例的方式三
static TRDataManager *_dataManagerByInit = nil;
+ (void)initialize {
if (self == [TRDataManager class]) {
//初始化操作;一定能保证只调用一次+线程安全的
_dataManagerByInit = [[TRDataManager alloc] init];
}
}
+ (instancetype)sharedDataManagerByInit {
return _dataManagerByInit;
}
创建单例
最新推荐文章于 2023-08-30 11:23:39 发布