单例模式写法和注释
本文最后更新于: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
方法,实现单例的内部逻辑