单例模式 是一个类在系统中只有一个实例对象。经过全局的一个入口点对这个实例对象进行访问。在iOS开发中,单例模式是很是有用的一种设计模式。设计模式
能够保证在程序运行过程,一个类只有一个实例工具
实现单例模式有三个条件:学习
类的构造方法是私有的spa
类提供一个类方法用于产生对象设计
类中有一个私有的本身对象code
针对于这三个条件,OC中都是能够作到的对象
类的构造方法是私有的
咱们只须要重写allocWithZone方法,让初始化操做只执行一次继承
类提供一个类方法产生对象
这个能够直接定义一个类方法内存
类中有一个私有的本身对象
咱们能够在.m文件中定义一个属性便可资源
应用场景
某个类常常被使用(节约系统资源)
定义工具类
共享数据
注意点
不要继承单例类
先建立子类永远是子类对象
先建立父类永远是父类对象
单例模式:
懒汉模式 : 第一次用到单例对象的时候再建立
饿汉模式 : 一进入程序就建立一个单例对象
#import "Singleton.h" @implementation Singleton static id _instance; /** * alloc方法内部会调用这个方法 */ + (instancetype)allocWithZone:(struct _NSZone *)zone{ if (_instance == nil) { // 防止频繁加锁 @synchronized(self) { if (_instance == nil) { // 防止建立屡次 _instance = [super allocWithZone:zone]; } } } return _instance; } + (instancetype)sharedSingleton{ if (_instance == nil) { // 防止频繁加锁 @synchronized(self) { if (_instance == nil) { // 防止建立屡次 _instance = [[self alloc] init]; } } } return _instance; } - (id)copyWithZone:(NSZone *)zone{ return _instance; } @end
#import "HMSingleton.h" @implementation Singleton static id _instance; /** * 当类加载到OC运行时环境中(内存),就会调用一次(一个类只会加载1次) */ + (void)load{ _instance = [[self alloc] init]; } + (instancetype)allocWithZone:(struct _NSZone *)zone{ if (_instance == nil) { // 防止建立屡次 _instance = [super allocWithZone:zone]; } return _instance; } + (instancetype)sharedSingleton{ return _instance; } - (id)copyWithZone:(NSZone *)zone{ return _instance; } @end
@implementation Singleton static id _instance; + (instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance; } + (instancetype)sharedSingleton{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[self alloc] init]; }); return _instance; } - (id)copyWithZone:(NSZone *)zone{ return _instance; } @end
在非ARC的环境下,须要再加上下面的方法:
重写release方法为空
重写retain方法返回本身
重写retainCount返回1
重写autorelease返回本身
- (oneway void)release { } - (id)retain { return self; } - (NSUInteger)retainCount { return 1;} - (id)autorelease { return self;}
如何判断是不是ARC
#if __has_feature(objc_arc) //ARC环境 #else //MRC环境 #endif
更多关于iOS学习开发的文章请登录个人我的博客www.zhunjiee.com,欢迎前来参观学习