单例在Objective-C和Swift中的实现

2017-01-22  本文已影响40人  楼上那只猫

Objective-C

@implementation MySingleInstance
static MySingleInstance * mysingle = nil;
+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mysingle = [[super allocWithZone:NULL] init];
    });
    return mysingle;
}
//alloc的时候会调用这个方法,重写使其直接调用上面的方法
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [MySingleInstance shareInstance];
}
//copy的时候会调用
- (instancetype)copyWithZone:(struct _NSZone *)zone {
    return [MySingleInstance shareInstance];
}
@end

Swift

class SwiftSingle: NSObject {
    var name = ""
    static let shared = SwiftSingle()
    private override init() {}  //重载初始化方法可以避免外部对象使用init方法创建另外一个实例
}

上一篇下一篇

猜你喜欢

热点阅读