OC:
+(instancetype)shareNetworkTools{ static id instance; static dispatch_once_t onceToken; //onceToken默认等于0,如果是0就执行block,如果不是就不执行 NSLog(@"%ld",onceToken); dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); return instance; }
Swift:
/* //在swift中,类方法中不允许定义静态变量 static var once_t: dispatch_once_t = 0 static var instance: NetworkTools? //用于获取单例对象的类方法 class func shareNetworkTools() -> NetworkTools{ print(once_t) dispatch_once(&once_t) { () -> Void in instance = NetworkTools() } return instance! } */
//swift中的let是线程安全的
static let instance: NetworkTools = NetworkTools()
class func shareNetworkTools() -> NetworkTools{
return instance
}
//init方法在需要的时候才创建
override init(){
super.init()
print("----------")
}