Swift - 单例模式

class ZRSingleton {

private let concurrentQueue = DispatchQueue(label: "ConcurrentQueue",  attributes: .concurrent, target: nil)
private var queueDic = [String: String]()

static let sharedInstance = ZRSingleton()
private init(){
    
}

func setDicValue(value: String, for key: String){
    
    concurrentQueue.async(flags: .barrier) {
        self.queueDic[key] = value
    }
}


func getDicValue(for key: String) -> String? {
    var result: String?
    
    concurrentQueue.sync {
        result = queueDic[key]
    }
    return result
}
}

vc

 func createPattern() {
    
    let single = ZRSingleton.sharedInstance;
    let single2 = ZRSingleton.sharedInstance;
    
    single.setDicValue(value: "11111", for: "Z")
    print(single.getDicValue(for: "Z") ?? "nil")
    //打印地址
    print("address:\(Unmanaged.passUnretained(single).toOpaque() )")
    print("address:\(Unmanaged.passUnretained(single2).toOpaque() )")
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS开发中过程中最熟悉的设计模式应该是单例模式,例如NotificationCenter通知中心、Applica...
    FlyElephant阅读 419评论 0 0
  • 1.单例如下 这里static这个静态常量,只会被创建一次,而且在需要的时候才会被创建 2.验证 控制台输出: 笑...
    拥抱月亮的大星星阅读 478评论 0 0
  • 1.第一种单例模式 2.第二种单例模式
    博行天下阅读 327评论 0 0
  • Swift单例模式 单例模式 单例模式的作用是解决“应用中只有一个实例”的一类问题。在Cocoa Touch框架中...
    spicyShrimp阅读 1,341评论 0 4
  • 如果当时在一起了,现在会怎样?常常会听到身边好友或是其他人在说这个话题。如果和当时的那个人在一起了,会是怎样?想象...
    陌阡紫阅读 1,051评论 0 2