单例模式-学习笔记

126 阅读1分钟

单例写法

static Singleton * _instance = nil;
@implementation Singleton

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone ];
    });
    return _instance;
}

+ (instancetype)sharedInstance {
    if (_instance == nil) {
        _instance = [[super alloc]init];
    }
    return _instance;
}

- (id)copyWithZone:(NSZone *)zone {
    return _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _instance;
}

写下面allocWithZone方法是为了防止下面代码,内存空间不一样。保证单例唯一性。

    Singleton *singleton = [Singleton sharedInstance];
    Singleton *singleton1 = [[Singleton alloc] init];
    Singleton *singleton2 = [singleton1 copy];