加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift中单例实现

发布时间:2020-12-14 02:04:46 所属栏目:百科 来源:网络整理
导读:首先,看下OC中一般单例实现: static NetWorkTool *tool; + ( instancetype )shareNetWorkTool { static dispatch_once_t onceToken; dispatch_once (onceToken,^{ tool = [[ self alloc ] init ]; }); return tool ; } Swift中一般单例实现: 写法一(这种
首先,看下OC中一般单例实现:
static NetWorkTool *tool;
+ (
instancetype )shareNetWorkTool {

static dispatch_once_t onceToken;
dispatch_once (&onceToken,^{
tool = [[ self alloc ] init ];
});

return tool ;
}

Swift中一般单例实现:

写法一(这种写法是参考OC中的实现思路):
static var tool: NetworkTool ?
var onceToken: dispatch_once_t = 0

class func sharedNetworkTool()-> NetworkTool {

dispatch_once (&onceToken) {
self .tool = NetworkTool ()
}

return tool!
}

但是,其实swift中,单例实现上不必那么麻烦了
写法二:
private static let tool = NetworkTool ()

class func sharedNetworkTool()-> NetworkTool {

return tool
}
就是这么简单,因为在swift中,let本身就是线程安全的,所以可以直接用!而且,这样的加载方式也是懒加载,是在第一次使用的时候创建的。
所以在实际用的时候直接用方法二就可以了!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读