首页 > 其他 > 详细

创建单例的正确姿势

时间:2017-11-24 14:48:09      阅读:248      评论:0      收藏:0      [点我收藏+]

方法 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")));

 

  

创建单例的正确姿势

原文:http://www.cnblogs.com/z-z-z/p/7890295.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!