美文网首页
Swift - 单例模式

Swift - 单例模式

作者: 是夏目啊 | 来源:发表于2017-08-23 11:27 被阅读0次
    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() )")
        
    }

    相关文章

      网友评论

          本文标题:Swift - 单例模式

          本文链接:https://www.haomeiwen.com/subject/hydddxtx.html