一、ARC中实现单粒模式
- 在.m 保留一个全局的static的实例 static id _名称;
- 重写allocWithZone:方法,在这里创建唯一的实例
- 提供一个类方法让外界访问唯一的实例
- 实现copyWithZone:方法 -- 方法中直接返回static修饰的全局变量,copy是对象方法,所以调用copy就说明已经有了单例对象
二、单粒模式 宏 的定义
- 定义一个.h文件就搞定
- 单粒模式使用
1 // .h文件 宏中的## 用来转译 2 #define XMGSingletonH(name) + (instancetype)shared##name; 3 4 // .m文件 宏的定义默认是一行,多行用,然后宏就能识别了 5 #define XMGSingletonM(name) 6 static id _instance; 7 8 + (instancetype)allocWithZone:(struct _NSZone *)zone 9 { 10 static dispatch_once_t onceToken; 11 dispatch_once(&onceToken, ^{ 12 _instance = [super allocWithZone:zone]; 13 }); 14 return _instance; 15 } 16 17 + (instancetype)shared##name 18 { 19 static dispatch_once_t onceToken; 20 dispatch_once(&onceToken, ^{ 21 _instance = [[self alloc] init]; 22 }); 23 return _instance; 24 } 25 26 - (id)copyWithZone:(NSZone *)zone 27 { 28 return _instance; 29 }