标签:
- 在IOS中有一个很重要的设计模式,那就是单例模式。何为单例模式呢?那就是至始至终它的内存地址都是只有一份。
实现:
- 普通方式:
static id _instance; + (instancetype)allocWithZone:(struct _NSZone *)zone { // 加入同步锁,防止多线程的情况下,同时进入创建实例 @synchronized(self){ if (_instance == nil) { _instance = [super allocWithZone:zone]; } return _instance; } } + (instancetype)sharedIntance { @synchronized(self){ if (_instance == nil) { _instance = [[self alloc] init]; } } return _instance; } - (id)copyWithZone:(NSZone *)zone { return _instance; }
- GCD形式创建
static id _instance; + (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance; } + (instancetype)sharedInstance { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[self alloc] init]; }); return _instance; } - (id)copyWithZone:(NSZone *)zone { return _instance; }
- 利用宏的形式创建,方便以后直接调用
// .h文件 #define SAMSingletonH(name) + (instancetype)shared##name; // .m文件 #define SAMSingletonM(name) \ static id _instance; + (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance; } + (instancetype)shared##name { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[self alloc] init]; }); return _instance; } - (id)copyWithZone:(NSZone *)zone { return _instance; }
标签:
原文地址:http://www.cnblogs.com/samyangldora/p/4631511.html