標籤:
單例:整個程式中只有一個執行個體,不論建立多少次,引用的都是同一個記憶體位址
以下是其實現方法,只要拷貝就可以直接用了(自己建立一個.h標頭檔,拷貝進去,調用的話在.h檔案使用WYSSingletonH(這裡寫你的類名),然後在.m檔案中調用WYSSingletonM(這裡寫你得類名),這裡包括了ARC和MRC的實現):
// .h檔案#define WYSSingletonH(name) +(instancetype)shared##name;// .m檔案#if __has_feature(objc_arc) #define WYSSingletonM(name) static id _instace; + (id)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super allocWithZone:zone]; }); return _instace; } + (instancetype)shared##name { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [[self alloc] init]; }); return _instace; } - (id)copyWithZone:(NSZone *)zone { return _instace; }#else #define WYSSingletonM(name) static id _instace; + (id)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super allocWithZone:zone]; }); return _instace; } + (instancetype)shared##name { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [[self alloc] init]; }); return _instace; } - (id)copyWithZone:(NSZone *)zone { return _instace; } - (oneway void)release { } - (id)retain { return self; } - (NSUInteger)retainCount { return 1;} - (id)autorelease { return self;}#endif
ios單例模式