首页 > 编程语言 > 详细

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

时间:2015-05-23 01:14:10      阅读:224      评论:0      收藏:0      [点我收藏+]

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     }

 

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

原文:http://www.cnblogs.com/haojuncong/p/4523518.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!