ARC下单例有两种写法
1.自己写加锁@synchronized(self)
2.运用GCD进行编写
下面是两种方法编写:
.h文件下代码
+ (instancetype)shareInstance;
.m文件下代码
static id _instace = nil;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
// 重新allocWithZone 这个方法 让alloc 出来的也单例对象
if (_instace == nil) { // 防止频繁的加锁
@synchronized(self) {
if (_instace == nil) {
_instace = [super allocWithZone:zone];
}
}
}
return _instace;}
+ (instancetype)shareInstance {
if (_instace == nil) { // 防止频繁的加锁
@synchronized(self) {
if (_instace == nil) { // 判断为空就创建
_instace = [[self alloc] init];
}
}
}
return _instace;}
//copy出来也是单例
- (id)copyWithZone:(NSZone *)zone {
return _instace;}
GCD方法
static id _instace = nil;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instace = [super allocWithZone:zone];
});
return _instace;}
+ (instancetype)shareInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instace = [[self alloc] init];
});
return _instace;}
- (id)copyWithZone:(NSZone *)zone {
return _instace;}
网友评论