单例模式是iOS开发中最常用的设计模式,iOS的单例模式有两种官方写法,如下:
#import "LGManagerCenter.h" static LGManagerCenter *managerCenter; @implementation LGManagerCenter +(LGManagerCenter *)sharedManager{ if(!managerCenter) managerCenter=[[self allocWithZone:NULL] init]; return managerCenter; } @end
#import "LGManagerCenter.h" @implementation LGManagerCenter +(LGManagerCenter *)sharedManager{ static dispatch_once_t predicate; static LGManagerCenter * managerCenter; dispatch_once(&predicate, ^{ managerCenter=[[LGManagerCenter alloc] init]; }); return managerCenter; } @end
其中dispatch_once函数只执行一次。
更多iOS开发相关技术请关注iOS开发微信公众号 iOS开发 :
iOSDevTip