單例:整個程序只建立一次,全局共用。安全
// 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