@chenbinghua
2015-09-12T02:33:38.000000Z
字数 1809
阅读 1619
iOS笔记
重写allocWithZone:方法,因为alloc内部调用allocWithZone:方法。这样类用alloc init或new创建的对象都是单例对象。
@implementation Personstatic Person *_person; // 强指针,对象永远不死// alloc内部调用allocWithZone:方法+ (instancetype)allocWithZone:(struct _NSZone *)zone{// 使用GCD的一次性代码static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{_person = [super allocWithZone:zone];});return _person;}
如[Person sharedPerson]
// .m文件增加此方法 .h文件添加此方法声明+ (instancetype)sharedPerson{static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{_person = [[self alloc] init];});return _person;}
若类遵循<NSCopying>协议,则需提供一下方法
- (id)copyWithZone:(NSZone *)zone{return _person;}
所有实现单例模式的类
+ (instancetype)sharedInstance;allocWithZone: sharedInstance copyWithZone:所以可以新创建一个Singleton.h文件,声明共有宏
// .h文件#define XMGSingletonH + (instancetype)sharedInstance;// .m文件#define XMGSingletonM \static id _instace; \\+ (instancetype)allocWithZone:(struct _NSZone *)zone \{ \static dispatch_once_t onceToken; \dispatch_once(&onceToken, ^{ \_instace = [super allocWithZone:zone]; \}); \return _instace; \} \\+ (instancetype)sharedInstance \{ \static dispatch_once_t onceToken; \dispatch_once(&onceToken, ^{ \_instace = [[self alloc] init]; \}); \return _instace; \} \\- (id)copyWithZone:(NSZone *)zone \{ \return _instace; \}
则上面的Person类可以这样定义
// .h文件#import <Foundation/Foundation.h>#import "Singleton.h"@interface Person : NSObjectXMGSingletonH@end// .m文件#import "Person.h"@interface Person()@end@implementation PersonXMGSingletonM@end
@implementation XMGPersonstatic id _instance;+ (instancetype)allocWithZone:(struct _NSZone *)zone{// 加上同步锁@synchronized(self) {if (_instance == nil) {_instance = [super allocWithZone:zone];}}return _instance;}+ (instancetype)sharedInstance{@synchronized(self) {if (_instance == nil) {_instance = [[self alloc] init];}}return _instance;}- (id)copyWithZone:(NSZone *)zone{return _instance;}@end