IOS :两种单例的创建

//gcd创建单例:

static id _instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone

{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

_instance = [superallocWithZone:zone];

});

return_instance;

}//保证oncetoken只被执行一次

+ (instancetype)sharedInstance

{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

_instance = [[self alloc] init];

});

return_instance;

}

- (id)copyWithZone:(NSZone *)zone

{

return_instance;

}

- (id)mutableCopyWithZone:(NSZone *)zone {

return_instance;

}

//互斥锁

static id _instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone

{

@synchronized(self) {

if(_instance == nil) {

_instance = [superallocWithZone:zone];

}//保证self对象不被其他进程修改 起到线程保护作用 同时括号内的代码块 会被加锁 其他线程访问会休眠 直到代码块执行结束或者抛出异常

}

return_instance;

}

+ (instancetype)sharedInstance

{

@synchronized(self) {

if(_instance == nil) {

_instance = [[self alloc] init];

}

}

return_instance;

}

- (id)copyWithZone:(NSZone *)zone

{

return_instance;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在开发中经常会用到单例设计模式,目的就是为了在程序的整个生命周期内,只会创建一个类的实例对象,而且只要程序不被杀死...
    零度_不结冰阅读 447评论 0 0
  • 原文地址 http://www.cocoachina.com/ios/20160907/17497.html 在开...
    Amok校长阅读 521评论 0 0
  • 单例模式的作用:可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问,从而方便地控制了实例个数,并...
    BEYOND黄阅读 302评论 0 3
  • 1、GCD方式创建单例 staticid_instance; +(instancetype)allocWithZo...
    乱尘阅读 646评论 0 0
  • 先啰嗦一下家里有多穷! 小时候家人从来不给零花钱,学费基本是这个学期快结束了,上个学期的学费还没交! 有一次爸给了...
    肖华生阅读 3,384评论 0 4