单例模式写法和注释
本文最后更新于:2 年前
单例的完整写法如下:
1 | |
- 仿照系统单例类,
.h文件中提供shareInstance的创建方法 - 使用
static修饰词创建静态变量,编译时分配内存,程序结束时释放内存 - 推荐使用
dispatch_once的线程方法为静态变量赋值,也可以使用@synchronized替代
1 | |
- 为了避免
[[AObject alloc] init]、[aObject new]、[aObject copy]、[aObject mutableCopy]的方法创建出其他对象,重写allocWithZone、copyWithZone、mutablecopyWithZone的方法,将其他创建的入口全部导入指定的shareInstance方法中 - 由于重写了
allocWithZone的方法,所以shareInstance中需要使用[super allocWithZone:NULL]进行内存分配 - 重写
init方法,实现单例的内部逻辑