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

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

例如写一个NetworkTools的单例

(1)OC写单例

 1 + (instancetype)sharedNetworkTools {
 2     static id instance;
 3     
 4     static dispatch_once_t onceToken;
 5     
 6     dispatch_once(&onceToken, ^{
 7         instance = [[self alloc] init];
 8         //这里可以做一些初始化
 9     });
10     
11     return instance;
12 }

 

 

(2)Swift写单例

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

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

 1  private static let instance : NetworkTools = {
 2            let netWorkTool = NetworkTools()
 3           //这里初始化属性
 4         
 5            return netWorkTool
 6     }()
 7     
 8     class func sharedNetworkTools() -> NetworkTools {
 9         return instance
10     }

 

posted on 2015-05-23 00:04  歌飘渺  阅读(579)  评论(0编辑  收藏  举报

导航