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.单例模式不能使用继承实现,否则所有子类创建的对象都将是第一个创建的对象
新闻热点
疑难解答