Objective-C中单例的正确开启方式

创建方式一: GCD创建

static id _instance = nil;

+ (instancetype)sharedInstance {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

- (id)copyWithZone:(NSZone *)zone {
    
    return _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    
    return _instance;
}

创建方式二: 互斥锁创建

static id _instance = nil;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {

    @synchronized(self) {
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    }
    return _instance;
}

+ (instancetype)sharedInstance {

    @synchronized(self) {        
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }    
    return _instance;
}
 - (id)copyWithZone:(NSZone *)zone {

    return _instance;
}
  • 单例创建之后我们还需要将原本的创建初始化方法屏蔽掉

方法一:在.h文件中声明禁止方法

+(instancetype) alloc __attribute__((unavailable("call other method instead")));
-(instancetype) init __attribute__((unavailable("call other method instead")));
+(instancetype) new __attribute__((unavailable("call other method instead")));

方法二:重载init、new

- (instancetype)init {

    [self doesNotRecognizeSelector:_cmd];
    return nil;
}
// -----或----- //
- (instancetype)init {
    return [self.class sharedInstance];
}
//------加------//
- (instancetype)new {
    return [self.class sharedInstance];
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,887评论 1 32
  • __block和__weak修饰符的区别其实是挺明显的:1.__block不管是ARC还是MRC模式下都可以使用,...
    LZM轮回阅读 8,755评论 0 6
  • 前言 Swift 贡献给社区 作者 关于中文翻译 条件语句 尤达表达式 nil 和 BOOL 检查 黄金大道 复杂...
    一条鱼的星辰大海阅读 3,017评论 0 1
  • 那一年大概是高三还是好朋友念高四,还是我们都已经在大学校园了,记不清了,反正我的高中同桌,跟着他的超级偶像张国荣一...
    静工皮匠阅读 1,823评论 0 1
  • 你会老,会沧桑,会在某一个时机悄然地离开,我不能厮守你的卧榻,只能在时光的另一个维度默默地期许。 如果世界有一抹阳...
    江誉伦阅读 1,382评论 0 0

友情链接更多精彩内容