您的位置:首页 > 其它

单例模式

2016-01-10 00:00 197 查看

单例模式-ARC

1.在.m中保留一个全局的static的实例
static id _instance;


2.重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)

+ (id)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if (!_instance) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}


3.提供1个类方法让外界访问唯一的实例

+ (instancetype)sharedSoundTool
{
@synchronized(self) {
if (!_instance) {
_instance = [[self alloc] init];
}
}
return _instance;
}


4.实现copyWithZone:方法

+ (id)copyWithZone:(struct _NSZone *)zone
{
return _instance;
}


单例模式 – MRC

非ARC中(MRC),单例模式的实现(比ARC多了几个步骤)

实现内存管理方法

- (id)retain { return self; }
- (NSUInteger)retainCount { return 1; }
- (oneway void)release {}
- (id)autorelease { return self; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: