1、ARC下的單例實現 |
說明:在用戶實例化的方法控制單次執行,同時開放單例的初始化方法。spa
-(instancetype)init{ self=[super init]; if(self){ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ }); } return self; } static id instance; +(instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance=[super allocWithZone:zone]; }); return instance; } + (instancetype) shareAudio{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance=[[self alloc]init]; }); return instance; } +(id)copyWithZone:(struct _NSZone *)zone{ return instance; }
2、MRC下的單例實現 |
說明:在用戶實例化的方法控制單次執行,同時開放單例的初始化方法,因爲當前爲MRC因此須要控制參內存管理的方法單次執行,所以相比ARC須要增長:code
static id instance; +(instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance=[super allocWithZone:zone]; }); return instance; } + (instancetype) shareAudio{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance=[[self alloc]init]; }); return instance; } -(oneway void)release{ } -(instancetype)autorelease{ return instance; } -(instancetype)retain{ return instance; } -(NSUInteger)retainCount{ return 1; }
3、兼容MRC 和ARC的宏定義 |
說明:爲了方便後期的引用,能夠將單例抽取爲宏定義,鑑於抽取的時候考慮到當前的手動計數和自動計數所以引入條件編譯:blog
#if !__has_feature(objc_arc) ======當前是ARC #else ======當前是MRC #endif 代碼: #define singleton_h(name) + (instancetype) share##name; #if !__has_feature(objc_arc) #define singleton_m(name)\ static id instance;\ +(instancetype)allocWithZone:(struct _NSZone *)zone{\ static dispatch_once_t onceToken;\ dispatch_once(&onceToken, ^{\ instance=[super allocWithZone:zone];\ });\ return instance;\ }\ \ \ + (instancetype) share##name{\ static dispatch_once_t onceToken;\ dispatch_once(&onceToken, ^{\ instance=[[self alloc]init];\ });\ return instance;\ }\ -(oneway void)release{\ }\ \ -(instancetype)autorelease{\ return instance;\ }\ \ -(instancetype)retain{\ return instance;\ }\ \ +(id)copyWithZone:(struct _NSZone *)zone{\ return instance;\ }\ -(NSUInteger)retainCount{\ return 1;\ } #else #define singleton_m(name)\ static id instance;\ +(instancetype)allocWithZone:(struct _NSZone *)zone{\ static dispatch_once_t onceToken;\ dispatch_once(&onceToken, ^{\ instance=[super allocWithZone:zone];\ });\ return instance;\ }\ \ \ + (instancetype) share##name{\ static dispatch_once_t onceToken;\ dispatch_once(&onceToken, ^{\ instance=[[self alloc]init];\ });\ return instance;\ }\ \ +(id)copyWithZone:(struct _NSZone *)zone{\ return instance;\ } #endif
4、文件引用 |
1 在.h文件引用singleton_h(audio);內存
2 在.m文件引用singleton_m(audio);it