单例:整个程序只建立一次,全局共用。安全
// SharedPerson.h 文件中
+ (instancetype)share;
// SharedPerson.m 文件中 static SharedPerson *_person; + (instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t predicate; dispatch_once(&predicate, ^{ _person = [super allocWithZone:zone]; }); return _person; } + (instancetype)share { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _person = [[self alloc]init]; }); return _person; }
- (id)copyWithZone:(NSZone *)zone { return _person; }
+ (instancetype)allocWithZone:(struct _NSZone *)zone : [SharedPerson alloc]分配对象内存时,实际会调此函数allocWithZone:(struct _NSZone *)zone,因此须要重写此方法来保证单例对象只会建立一次,并且是必须重写此方法,防止其余开发者直接用初始化方法来建立单例对象。函数
- (id)copyWithZone:(NSZone *)zone : 此函数来保证单例对象能够copy再获得一个如出一辙的对象。spa