IOS之单例,你真的会写单例么?
2019-08-22 本文已影响0人
勇敢的我2017
一、草草写法
先附上不大部分人的写法
SingleModel.h

SingleModel.m

测试代码:

打印结果:

通过上边的测试,可以看出来通过alloc创建对象时,是有问题的,所以要封锁初始化的方法
如alloc, copy,mutableCopy,new
原理:
创建对象的步骤分为申请内存(alloc)、初始化(init)这两个步骤,我们要确保对象的唯一性,因此在第一步这个阶段我们就要拦截它。当我们调用alloc方法时,OC内部会调用allocWithZone这个方法来申请内存,我们覆写这个方法,然后在这个方法中调用shareInstance方法返回单例对象,这样就可以达到我们的目的。拷贝对象也是同样的原理,覆写copyWithZone方法,然后在这个方法中调用shareInstance方法返回单例对象
二 、正确写法

1、shareInstance单例方法中,变量的初始化改成[[super allocWithZone:NULL] init]
2、实现copyWithZone:和mutableCopyWithZone:方法
测试代码:

打印结果:

无论通过哪种方式创建出来的实例对象,其内存地址都是一样的,所以该种写法才是严谨的。