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

swift单例

发布时间:2020-12-14 02:43:00 所属栏目:百科 来源:网络整理
导读:SwiftSingleton tl;dr: Use the class constant approach if you are using Swift 1.2 or above and the nested struct approach if you need to support earlier versions. An exploration of the Singleton pattern in Swift. All approaches below suppor

SwiftSingleton

tl;dr: Use theclass constantapproach if you are using Swift 1.2 or above and thenested structapproach if you need to support earlier versions.

An exploration of the Singleton pattern in Swift. All approaches below support lazy initialization and thread safety.

Issues and pull requests welcome.

Approach A: Class constant

class SingletonA {

    static let sharedInstance = SingletonA()

    init() {
        println("AAA");
    }

}

This approach supports lazy initialization because Swift lazily initializes class constants (and variables),and is thread safe by the definition oflet.(上述代表也实现了延迟加载技术)

Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift,use the nested struct approach below or a global constant.(早期版本支持,几乎不需要)

Approach B: Nested struct

class SingletonB { class var sharedInstance: SingletonB { struct Static { let instance: SingletonB = SingletonB() } return Static.instance } }

Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier,and still works as a workaround for the lack of static constants and variables in functions.

Approach C: dispatch_once

The traditional Objective-C approach ported to Swift.

class SingletonC { var sharedInstance: SingletonC { var onceToken: dispatch_once_t = 0 var instance: SingletonC? = nil } dispatch_once(&Static.onceToken) { Static.instance = SingletonC() } .instance! } }

I'm fairly certain there's no advantage over the nested struct approach but I'm including it anyway as I find the differences in syntax interesting.(使用GCD技术实现的单例模式)

(编辑:李大同)

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

    推荐文章
      热点阅读