iOS开发 单例模式

我们先看下函数void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);其中第一个参数predicate,该参数是检查后面第二个参数所代表的代码块是否被调用的谓词,第二个参数则是在整个应用程序中只会被调用一次的代码块。

dispach_once函数中的代码块只会被执行一次,而且还是线程安全的。

接下来我们自己编写一个单例

这种加锁的方式虽然是线程安全,但不是运行最快的

+ (instancetype)shareManager{

   @synchronized(self){

       if(!manager) {

            manager = [[selfalloc]init];

        }

       returnmanager;

    }

}

第二种利用dispatch_once 所以一个完善的单例是这样

1,使用alloc方法初始化一个类的实例的时候,默认是调用了 allocWithZone 的方法

2,如果单例创建的时候利用alloc,或者copy ,都是调用shareInstance的方法,保证唯一。

static Singleton* _instance =nil;

+(instancetype) shareInstance

{

   staticdispatch_once_tonceToken ;

   dispatch_once(&onceToken, ^{

        _instance = [[superalloc WithZone:NULL] init] ;

    }) ;

   return_instance ;

}

+(id) allocWithZone:(struct_NSZone*)zone

{

   return[Singleton shareInstance] ;

}

-(id) copyWithZone:(NSZone*)zone

{

   return[Singleton shareInstance] ;

}

-(id) mutablecopyWithZone:(NSZone*)zone

{

   return[Singleton shareInstance] ;

}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容