创建单例的正确姿势

方法 1:

  声明 :+ (instancetype)sharedInstance  单例方法

  重写:+ (instancetype)allocWithZone:(struct _NSZone *)zone+(instancetype)alloc+(instancetype)new 都会走 allocWithZone ,多以直接重写 allocWithZone 就ok了)

     - (instancetype)copy

       - (instancetype)mutableCopy

  完整代码:

+ (instancetype)sharedInstance {
    
    static MyPerson *person = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        person = [[super allocWithZone:nil] init];
    });
return person; } + (instancetype)allocWithZone:(struct _NSZone *)zone {
return [MyPerson sharedInstance]; } - (instancetype)copy {
return [MyPerson sharedInstance]; } - (instancetype)mutableCopy {
return [MyPerson sharedInstance]; }

方法 2:

  声明:+ (instancetype)sharedInstance  单例方法

  然后让其他可能创建该对象的方法不可用,这里使用到  __attribute__  。这样在调用下列方法时,编译会报错。

  完整代码:

+ (instancetype)sharedInstance;
+ (instancetype) alloc __attribute__((unavailable("use sharedInstance")));
+ (instancetype) new __attribute__((unavailable("use sharedInstance")));
- (instancetype) copy __attribute__((unavailable("use sharedInstance")));
- (instancetype) mutableCopy __attribute__((unavailable("use sharedInstance")));

 

  

posted @ 2017-11-24 14:01  zzlei  阅读(174)  评论(0编辑  收藏  举报