美文网首页
iOS开发ARC下的单例

iOS开发ARC下的单例

作者: Scheng_ | 来源:发表于2017-04-24 11:01 被阅读0次

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;}

相关文章

网友评论

      本文标题:iOS开发ARC下的单例

      本文链接:https://www.haomeiwen.com/subject/neguzttx.html