IOS 中两种单例模式的写法实例详解
iOS的单例模式有两种官方写法,如下:
(1)不使用GCD
#import"ServiceManager.h" staticServiceManager*defaultManager; @implementationServiceManager +(ServiceManager*)defaultManager{ if(!defaultManager) defaultManager=[[selfallocWithZone:NULL]init]; returndefaultManager; } @end
(2)使用GCD
#import"ServiceManager.h" @implementationServiceManager +(ServiceManager*)sharedManager{ staticdispatch_once_tpredicate; staticServiceManager*sharedManager; dispatch_once(&predicate,^{ sharedManager=[[ServiceManageralloc]init]; }); returnsharedManager; } @end
dispatch_once这个函数,它可以保证整个应用程序生命周期中某段代码只被执行一次!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!