工作生活

单例模式的使用

2019-07-04  本文已影响0人  0fbf551ff6fb

new和alloc/init的区别 从_alloc和_zoneAlloc中可以看出,alloc 使用了_zoneAlloc , 它是给对象分配内存的时候,把关联的对象分配到一个相邻的内存区域内,以便于调用时消耗很少的代价,提升了程序处理速度。但如果使用new的话,初始化方法被固定死只能调用init.不能再使用init开头的其它初始化方法,

alloc和allocWithZone都是创建一个类实例的方法

不同之处在于,alloc无法指定一个NSZone来存储自己创建的实例,它最终调用的是allocWithZone(nil),使用的是系统给定的NSZone

allocWithZone可以指定自己的NSZone来存储自己创建的实例,如果zone传nil 它使用的就是系统给定的NSZone

+(instancetype)shareInsterse{

    static DanliModel *_model;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _model = [[super allocWithZone:NULL]init];

    });

    return _model;

}

+(instancetype)allocWithZone:(struct _NSZone *)zone {

    return [self shareInsterse];

}

- (instancetype)copyWithZone:(NSZone *)zone {

    return self;

}

// mutableCopy 方法调用

- (instancetype)mutableCopyWithZone:(NSZone *)zone {

    return self;

}

上一篇 下一篇

猜你喜欢

热点阅读