(0088)iOS开发之单例的写法以及重新认识

首先看下经常的写法:

注明:dispatch_once这个函数,  它可以保证整个应用程序生命周期中某段代码只被执行一次!且线程安全,所以也能够用它实现单例的线程安全
Singleton.h
 
@interface Singleton : NSObject
 
+(instancetype) shareInstance ;
 
@end
 
 
 
#import "Singleton.h"
 
@implementation Singleton
 
static Singleton* _instance = nil;
 
+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init] ;
        //或者 _instance = [[Singleton alloc] init] ;
    }) ;
     
    return _instance ;
}
 
@end

上面写法大多数通过

Singleton* obj2 = [Singleton shareInstance] ;创建的实例是没有问题的,

但是如果通过

Singleton* obj3 = [[Singleton alloc] init] ;来创建就发现依然会创建新的实例。

所以为了避免这个问题;安全写法如下:

#import "Singleton.h"
@interface Singleton()<NSCopying,NSMutableCopying>
@end
 
@implementation Singleton
 
static Singleton* _instance = nil;
 
+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:NULL] init] ;
        //不是使用alloc方法,而是调用[[super allocWithZone:NULL] init] 
        //已经重载allocWithZone基本的对象分配方法,所以要借用父类(NSObject)的功能来帮助出处理底层内存分配的杂物
    }) ;
     
    return _instance ;
}
 
+(id) allocWithZone:(struct _NSZone *)zone
{
    return [Singleton shareInstance] ;
}
 
-(id) copyWithZone:(NSZone *)zone
{
    return [Singleton shareInstance] ;
}
 
-(id) mutablecopyWithZone:(NSZone *)zone
{
    return [Singleton shareInstance] ;
}
@end

可以看到,当我们调用shareInstance方法时获取到的对象是相同的,但是当我们通过alloc和init以及copy来构造对象的时候,依然会创建新的实例。
要确保对象的唯一性,所以我们就需要封锁用户通过alloc和init以及copy来构造对象这条道路。
我们知道,创建对象的步骤分为申请内存(alloc)、初始化(init)这两个步骤,我们要确保对象的唯一性,因此在第一步这个阶段我们就要拦截它。当我们调用alloc方法时,oc内部会调用allocWithZone这个方法来申请内存,我们覆写这个方法,然后在这个方法中调用shareInstance方法返回单例对象,这样就可以达到我们的目的。拷贝对象也是同样的原理,覆写copyWithZone方法,然后在这个方法中调用shareInstance方法返回单例对象。

测试代码:

Singleton* obj1 = [Singleton shareInstance] ;
NSLog(@"obj1 = %@.", obj1) ;

Singleton* obj2 = [Singleton shareInstance] ;
NSLog(@"obj2 = %@.", obj2) ;

Singleton* obj3 = [[Singleton alloc] init] ;
NSLog(@"obj3 = %@.", obj3) ;

Singleton* obj4 = [[Singleton alloc] init] ;
NSLog(@"obj4 = %@.", [obj4 copy]) ;

Singleton* obj5 = [[Singleton alloc] init] ;
NSLog(@"obj5 = %@.", [obj5 mutableCopy]) ;

Singleton* obj6 = [[Singleton new] ;
NSLog(@"obj6 = %@.", obj6) ;

注意: 如果实现 allocWithZone  方法,dispatch_once 中一定要用 _instance = [[super allocWithZone:NULL] init] ;

不能用        _instance = [[self alloc]init]; 或者_instance = [[super alloc]init];因为会造成死循环。


一切起源于Apple官方文档里面关于单例(Singleton)的示范代码:Creating a Singleton Instance.

扫描二维码关注公众号,回复: 6149519 查看本文章

http://www.cocoachina.com/bbs/read.php?tid=116873&fpage=33

https://www.jianshu.com/p/6b012ebc10fe

有个宏的写法很好:传送门

猜你喜欢

转载自blog.csdn.net/shifang07/article/details/87160573