HWWY

导航

ARC单例模式的实现

使用alloc方法初始化一个类的实例的时候,默认是调用了 allocWithZone 的方法。

重写allocWithZone方法\

//重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)

static id _instance;

+(instancetype)alloc

{

    return [super allocWithZone:nil];

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

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instance = [super allocWithZone:zone];

    });

    return _instance;

}

//提供1个类方法让外界访问唯一的实例

+ (instancetype)sharedInstance

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instance = [[self alloc] init];

    });

    return _instance;

}

 

 

//实现copyWithZone:方法

- (id)copyWithZone:(struct _NSZone *)zone

{

    return _instance;

}

posted on 2019-07-18 18:14  HWWY  阅读(149)  评论(0编辑  收藏  举报