美文网首页
ios 确保单例对象的唯一性

ios 确保单例对象的唯一性

作者: pipiOU | 来源:发表于2019-11-22 17:52 被阅读0次

    之前创建单例是使用下面的方式:

    
    + (instancetype)shareHandle{
    
    static SingleHandle *share = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
    
    share = [[SingleHandle alloc] init];
    
    });
    
    return share;
    
    }
    
    

    这种方式创建的单例,如果外部使用了alloc方法来创建实例,或者copy方法拷贝了单例实例,那么就无法确保对象的唯一性,因此需要重写allocWithZone:和copyWithZone:方法来规避外部创建多个单例对象。

    + (instancetype)shareHandle{
        static SingleHandle *share = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            share = [[super allocWithZone:NULL] init];    });
        return share;
    }
    
    //规避外部使用alloc方法创建实例
    + (instancetype)allocWithZone:(struct _NSZone *)zone
    {
        return [self shareHandle];
    }
    
    //规避外部使用copy操作来创建单例对象
    - (id)copyWithZone:(NSZone *)zone
    {
        return self;
    }
    
    

    说明:
    1.在调用alloc方法时,OC内部会调用allocWithZone:这个方法来申请内存.

    2.NSObject虽然有copy 和 mutableCopy方法,但是并没有实现,需要在子类中遵循NSCopying协议,即实现copyWithZone:方法.

    相关文章

      网友评论

          本文标题:ios 确保单例对象的唯一性

          本文链接:https://www.haomeiwen.com/subject/elvqwctx.html