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
}