標籤:
// 協助實現單例設計模式// .h檔案的實現#define SingletonH(methodName) + (instancetype)shared##methodName;// .m檔案的實現#if __has_feature(objc_arc) // 是ARC#define SingletonM(methodName) static id _instace = nil; + (id)allocWithZone:(struct _NSZone *)zone { if (_instace == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super allocWithZone:zone]; }); } return _instace; } - (id)init { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super init]; }); return _instace; } + (instancetype)shared##methodName { return [[self alloc] init]; } + (id)copyWithZone:(struct _NSZone *)zone { return _instace; } + (id)mutableCopyWithZone:(struct _NSZone *)zone { return _instace; }#else // 不是ARC#define SingletonM(methodName) static id _instace = nil; + (id)allocWithZone:(struct _NSZone *)zone { if (_instace == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super allocWithZone:zone]; }); } return _instace; } - (id)init { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super init]; }); return _instace; } + (instancetype)shared##methodName { return [[self alloc] init]; } - (oneway void)release { } - (id)retain { return self; } - (NSUInteger)retainCount { return 1; } + (id)copyWithZone:(struct _NSZone *)zone { return _instace; } + (id)mutableCopyWithZone:(struct _NSZone *)zone { return _instace; }#endif
將上述代碼放進放到.h標頭檔中
使用方法:在單例的檔案中,.h中實現SingletonH(mothodName)(methodName為方法名)
.m中實現SingletonM(mothodName)
iOS開發之單例標頭檔