ios专题iOS开发

单例

2016-07-14  本文已影响31人  HeavenWong

OC中的单例

+ (instancetype)sharedManager {
    static id instance;

    static dispatch_once_t onceToken;
    NSLog(@"%ld", onceToken);

    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });

    return instance;
}

swift中的单例

static var instance: NetworkTools?
static var token: dispatch_once_t = 0

/// 在 swift 中类变量不能是存储型变量
class var sharedNetworkTools: NetworkTools {
    dispatch_once(&token, { () -> Void in
        self.instance = NetworkTools()
    })

    return self.instance!
}

swift改进过的单例

private static let instance = NetworkTools()
/// 在 swift 中类变量不能是存储型变量
class var sharedNetworkTools: NetworkTools {
    return instance
}

上一篇 下一篇

猜你喜欢

热点阅读