【Swfit】Swift与OC两种语法写单例的区别

时间:2023-03-09 06:50:11
【Swfit】Swift与OC两种语法写单例的区别

Swift与OC两种语法写单例的区别

例如写一个NetworkTools的单例

(1)OC写单例

 + (instancetype)sharedNetworkTools {
static id instance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
//这里可以做一些初始化
}); return instance;
}

(2)Swift写单例

     // 定义一个私有的静态成员
// `let` 就是线程安全的
// 这句代码懒加载的,在第一次调用的时候,才会运行
private static let instance = NetworkTools() class func sharedNetworkTools() -> NetworkTools {
return instance
}

假如要预先初始化一些属性,则可以这么写

  private static let instance : NetworkTools = {
let netWorkTool = NetworkTools()
//这里初始化属性 return netWorkTool
}() class func sharedNetworkTools() -> NetworkTools {
return instance
}