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

对比Swift和Objective_C中单例的写法

发布时间:2020-12-14 07:07:19 所属栏目:百科 来源:网络整理
导读:创建一个NetWorkTools的类 Objective_C: NetWorkTools.h中 + (instancetype)shareNetWorkTools; NetWorkTools.m中 + (instancetype)shareNetWorkTools{ static id instance; static dispatch_once_t onceToken; // onceToken默认等于0,如果是0就会执行block,

创建一个NetWorkTools的类

Objective_C:

NetWorkTools.h中

+ (instancetype)shareNetWorkTools;

NetWorkTools.m中

+ (instancetype)shareNetWorkTools
{
    static id instance;
    static dispatch_once_t onceToken;
    // onceToken默认等于0,如果是0就会执行block,如果不是0就不会执行
    dispatch_once(&onceToken,^{
        instance = [[self alloc] init];
    });
    return instance;
}

Swift:

传统写法

// 在Swift中,类方法中是不允许定义静态变量的
 static var once_t: dispatch_once_t = 0
 static var instance: NetWorkTools?

 // 用于获取单例对象的类方法
 class func shareNetWorkTools() -> NetWorkTools{

 dispatch_once(&once_t) { () -> Void in
 instance = NetWorkTools()
 }
 return instance!
 }

简单写法

//Swift中的let是线程安全的,用到时才会创建
static let instance: NetWorkTools = NetWorkTools()
class func shareNetWorkTools() -> NetWorkTools { return instance }

(编辑:李大同)

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

    推荐文章
      热点阅读