Xcode
1、单例模式的作用可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问;从而方便地控制了实例个数,并节约系统资源
2、单例模式的使用场合在整个应用程序中,共享一份资源(这份资源只需要创建初始化 1 次)
3、单例模式在 ARC\MRC 环境下的写法有所不同,需要编写 2 套不同的代码
3.1 可以用宏判断是否为 ARC 环境#if __has_feature(objc_arc)// ARC#else// MRC#endif
3.2 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)sharedDemo{ @synchronized(self) { if (!_instance) { _instance = [[self alloc] init]; } } return _instance;}
3.3 非ARC中(MRC),单例模式的实现(比ARC多了几个步骤)(1)实现内存管理方法- (id)retain { return self; }- (NSUInteger)retainCount { return 1; }- (oneway void)release {}- (id)autorelease { return self; }
4、具体实现
4.1新建一个项目,名为“单例设计模式”
4.2新建一个名为“SingletonDemo”的类,继承自“NSObject”
4.3在类的头文件中设计一个创建单例对象的类方法:+ (instancetype)sharedSingletonDemo;
4.4在类的.m文件中实现相应的方法#import 'SingletonDemo.h' @implementation SingletonDemo // 定义一个全局的static的实例static id _instance; /** * 重写allocWithZone:方法,在这里创建唯一的实例 */+ (id)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance;} /** * 提供一个给外部调用的实例化类方法 */+ (instancetype)sharedSingletonDemo{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[self alloc] init]; }); return _instance;} /** * 为了考虑得更全面一些,把copy策略创建对象的方法也重写一遍 */+ (id)copyWithZone:(struct _NSZone *)zone{ return _instance;}@end
如果您觉得这篇经验有用的话,麻烦投上您宝贵的一票,当然您也可以收藏哦!