标签:
单例:整个程序中只有一个实例,不论创建多少次,引用的都是同一个内存地址
以下是其实现方法,只要拷贝就可以直接用了(自己创建一个.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
标签:
原文地址:http://www.cnblogs.com/GeekStar/p/4398135.html