在IOS中,所有对象的内存分配的方法都会调用allocWithZone,比如构造函数alloc,所以重写这个方法就可以实现单例。
Xcode中预先写好了实现代码的快捷指令,敲dispatch_once就会看到。这个是有GCD实现的单例代码。
实现代码如下:
+(id)allocWithZone:(struct _NSZone *)zone{ static LYDemo * instance; //是线程安全的,onceToKen默认是0 static dispatch_once_t onceToken; //dispatch_once宏可以保证代码中的代码只会被执行一次。 dispatch_once(&onceToken, ^{ instance = [super allocWithZone:zone]; }); return instance;}//上面代码只是保证了这个类只能有一个实例,而易读性略差,我们应该模仿系统的单例方式。+(instancetype)sharedDemo{ return [[self alloc]init];}
实现单例的步骤:
1.重写allocWithZone方法,使用GCD预先写好的代码块dispatch_once snippet。
2.创建一个以shared开头的方法,模仿系统的单例。