【Swfit】Swift与OC两种语法写单例的区别
2015-05-23 00:04
561 查看
Swift与OC两种语法写单例的区别
例如写一个NetworkTools的单例
(1)OC写单例
(2)Swift写单例
假如要预先初始化一些属性,则可以这么写
例如写一个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 }
相关文章推荐
- Vickate_Swift2.0的方法总结 及 与C/OC的语法区别
- Swift与OC语言中语法的一些区别
- swift3 与 OC 语法区别
- [swift、oc]浅聊nil、Nil、NULL、NSNull的区别
- oc转swift基本语法一
- Swift的String与OC的NSString的区别
- Swift与OC语法对比
- 走进swfit(三)Swift调用OC
- iOS笔记--oc语法8 (@synthesize和@dynamic的区别)
- Swift的数组与OC中数组的区别
- swift 和oc的部分小区别
- OC -- @interface和@property两种声明变量方式的区别
- Swift语法之 ---- ?和!区别
- OC与Swift的区别五(函数)
- 走进swfit(五)OC调用Swift
- Swift语法之 ---- ?和!区别
- addTarget事件添加方法在OC和Swift中的区别
- OC -- @interface和@property两种声明变量方式的区别
- swift-01-简述swift与OC区别
- swift中cell的两种创建区别和extension的使用。让我们开发更有条理