share方法
+ (instancetype)sharePerson{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _person = [[self alloc] init]; }); return _person;}
alloc方法
+ (instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _person = [super allocWithZone:zone]; }); return _person;}
copy方法
- (id)copyWithZone:(NSZone *)zone{ return _person;}
代碼如下:
//.h文件#define LYPSingletonH(name) + (instancetype)share##name;//.m文件#define LYPSingletonM(name) /static id _instance; / /+ (instancetype)share##name /{ / static dispatch_once_t onceToken; / dispatch_once(&onceToken, ^{ / _instance = [[self alloc] init]; / }); / return _instance; /} / /+ (instancetype)allocWithZone:(struct _NSZone *)zone /{ / static dispatch_once_t onceToken; / dispatch_once(&onceToken, ^{ / _instance = [super allocWithZone:zone]; / }); / return _instance; /} / /- (id)copyWithZone:(NSZone *)zone /{ / return _instance; /}
注意事項
實現代碼如下
static Dog *_dog;+ (instancetype)shareDog{ @synchronized(self) { if (_dog == nil) { [NSThread sleepForTimeInterval:3]; _dog = [[self alloc] init]; } } return _dog;}+ (instancetype)allocWithZone:(struct _NSZone *)zone{ @synchronized(self) { if (_dog == nil) { [NSThread sleepForTimeInterval:3]; _dog = [super allocWithZone:zone]; } } return _dog;}- (id)copyWithZone:(NSZone *)zone{ return _dog;}
注意事項
1.單例模式不能使用繼承實現,否則所有子類創建的對象都將是第一個創建的對象
新聞熱點
疑難解答