1. 单例在ARC中的实现
ARC中单例实现步骤
- 在类的内部提供一个static修饰的全局变量
- 提供一个类方法,方便外界访问
- 重写
+allocWithZone
方法,保证永远都只为单例对象分配一次内存空间 - 严谨起见,重写
-copyWithZone
方法和-MutableCopyWithZone
方法
ARC中单例代码实现
#import "Tools.h"
@implementation Tools
// 创建静态对象 防止外部访问
static Tools *_instance = nil;
+(instancetype)allocWithZone:(struct _NSZone *)zone{
// @synchronized (self) {
// // 为了防止多线程同时访问对象,造成多次分配内存空间,所以要加上线程锁
// if (_instance == nil) {
// _instance = [super allocWithZone:zone];
// }
// return _instance;
// }
// 也可以使用一次性代码
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
});