iOS中的单例模式


概念相关

单例模式在程序运行过程,一个类只有一个实例使用场合在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)static


static关键字会在声明变量的时候分配内存,在程序运行期间只分配一次内存。之后再访问时,实际都是在访问原先分配的内存如果使用static来修饰局部变量,那么局部变量在代码块结束后将不会回收,下次使用保持上次使用后的值。如果使用static来修饰全局变量,那么表示该全局变量只在本文件中有效,外界无法使用extern来引用。static变量的作用域被限制在定义变量的当前文件中,其它文件是不能访问的。ARC实现单例


步骤

01 在类的内部提供一个static修饰的全局变量02 提供一个类方法,方便外界访问03 重写+allocWithZone方法,保证永远都只为单例对象分配一次内存空间04 严谨起见,重写-copyWithZone方法和-MutableCopyWithZone方法

源码

static ZCTools *_instance;+ (instancetype)shareTools{    return [[self alloc]init];}+ (instancetype)allocWithZone:(struct _NSZone *)zone{    @synchronized(self) {        if (_instance == nil) {            _instance = [super allocWithZone:zone];        }    }    return _instance;}- (nonnull id)copyWithZone:(nullable NSZone *)zone{    return _instance;}- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone{    return _instance;}

代码分析

//提供一个static修饰的全局变量,强引用着已经实例化的单例对象实例static ZCTools *_instance;//类方法,返回一个单例对象+ (instancetype)shareTools{     //注意:这里建议使用self,而不是直接使用类名Tools(考虑继承)    return [[self alloc]init];}//保证永远只分配一次存储空间+(instancetype)allocWithZone:(struct _NSZone *)zone{    //使用GCD中的一次性代码//    static dispatch_once_t onceToken;//    dispatch_once(&onceToken, ^{//        _instance = [super allocWithZone:zone];//    });    //使用加锁的方式,保证只分配一次存储空间    @synchronized(self) {        if (_instance == nil) {            _instance = [super allocWithZone:zone];        }    }    return _instance;}/*1. mutableCopy 创建一个新的可变对象,并初始化为原对象的值,新对象的引用计数为 1;2. copy 返回一个不可变对象。分两种情况:(1)若原对象是不可变对象,那么返回原对象,并将其引用计数加 1 ;(2)若原对象是可变对象,那么创建一个新的不可变对象,并初始化为原对象的值,新对象的引用计数为 1。*///让代码更加的严谨- (nonnull id)copyWithZone:(nullable NSZone *)zone{//    return [[self class] allocWithZone:zone];    return _instance;}- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone{    return _instance;}

MRC实现单例


步骤

01 在类的内部提供一个static修饰的全局变量02 提供一个类方法,方便外界访问03 重写+allocWithZone方法,保证永远都只为单例对象分配一次内存空间04 严谨起见,重写-copyWithZone方法和-MutableCopyWithZone方法05 重写release方法06 重写retain方法07 建议在retainCount方法中返回一个最大值

配置MRC环境

01 注意ARC不是垃圾回收机制,是编译器特性02 配置MRC环境:build setting ->搜索automatic ref->修改为NO

源码

static ZCTools *_instance;+ (instancetype)shareTools{    return [[self alloc]init];}+ (instancetype)allocWithZone:(struct _NSZone *)zone{    @synchronized(self) {        if (_instance == nil) {            _instance = [super allocWithZone:zone];        }    }    return _instance;}- (nonnull id)copyWithZone:(nullable NSZone *)zone{    return _instance;}- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone{    return _instance;}- (oneway void)release{}- (instancetype)retain{    return _instance;}- (NSUInteger)retainCount{    return MAXFLOAT;}

代码分析

//提供一个static修饰的全局变量,强引用着已经实例化的单例对象实例static ZCTools *_instance;//类方法,返回一个单例对象+ (instancetype)shareTools{     //注意:这里建议使用self,而不是直接使用类名Tools(考虑继承)    return [[self alloc]init];}//保证永远只分配一次存储空间+ (instancetype)allocWithZone:(struct _NSZone *)zone{    //使用GCD中的一次性代码//    static dispatch_once_t onceToken;//    dispatch_once(&onceToken, ^{//        _instance = [super allocWithZone:zone];//    });    //使用加锁的方式,保证只分配一次存储空间    @synchronized(self) {        if (_instance == nil) {            _instance = [super allocWithZone:zone];        }    }    return _instance;}//让代码更加的严谨- (nonnull id)copyWithZone:(nullable NSZone *)zone{//    return [[self class] allocWithZone:zone];    return _instance;}- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone{    return _instance;}//在MRC环境下,如果用户retain了一次,那么直接返回instance变量,不对引用计数器+1//如果用户release了一次,那么什么都不做,因为单例模式在整个程序运行过程中都拥有且只有一份,程序退出之后被释放,所以不需要对引用计数器操作- (oneway void)release{}- (instancetype)retain{    return _instance;}//惯用法,有经验的程序员通过打印retainCount这个值可以猜到这是一个单例- (NSUInteger)retainCount{    return MAXFLOAT;}

通用版本


可以考虑一份单例代码在ARC和MRC环境下都适用(使用条件编译来判断当前项目环境是ARC还是MRC)

#if __has_feature(objc_arc)//如果是ARC,那么就执行这里的代码1#else//如果不是ARC,那么就执行代理的代码2#endif

在项目里面往往需要实现很多的单例,比如下载、网络请求、音乐播放等等,单例是否可用继承呢?

单例是不可继承,想一劳永逸可使用带参数的宏定义

使用带参数的宏完成通用版单例模式代码

注意条件编译的代码不能包含在宏定义里面宏定义的代码只用写一次,之后直接拖到项目中用就OK

#define SingleH(name)  +(instancetype)share##name;//ARC#if __has_feature(objc_arc)#define SingleM(name) static id _instance;\+(instancetype)allocWithZone:(struct _NSZone *)zone\{\    static dispatch_once_t onceToken;\    dispatch_once(&onceToken, ^{\        _instance = [super allocWithZone:zone];\    });\    return _instance;\}\+(instancetype)share##name\{\    return [[self alloc]init];\}\-(id)copyWithZone:(NSZone *)zone\{\    return _instance;\}\\-(id)mutableCopyWithZone:(NSZone *)zone\{\    return _instance;\}#else//MRC#define SingleM(name) static id _instance;\+(instancetype)allocWithZone:(struct _NSZone *)zone\{\static dispatch_once_t onceToken;\dispatch_once(&onceToken, ^{\_instance = [super allocWithZone:zone];\});\return _instance;\}\+(instancetype)share##name\{\return [[self alloc]init];\}\-(id)copyWithZone:(NSZone *)zone\{\return _instance;\}\\-(id)mutableCopyWithZone:(NSZone *)zone\{\return _instance;\}\-(oneway void)release\{\}\\-(instancetype)retain\{\    return _instance;\}\\-(NSUInteger)retainCount\{\    return MAXFLOAT;\}#endif

如果雨后还是雨,如果忧伤过后还是忧伤,

iOS中的单例模式

相关文章:

你感兴趣的文章:

标签云: