• Swift 学习笔记 (解决Swift闭包中循环引用的三种方法)


    话不多说 直接上代码

    class SmartAirConditioner {
        var temperature:Int = 26
        //类引用了函数
        var temperatureChange:((Int)->())!
        
        init() {
            /*
             [weak self] 表示 self为可选型 可以为nil 所以在使用的时候必须解包
             [unowned self]由于在使用前要保证一定有这个对象 所以不必解包
             
             */
    //        //这是类似于oc的解决方法。
    //        weak var tempSelf = self
    //        temperatureChange = {newTemperture in
    //            if abs(newTemperture - (tempSelf?.temperature)!) >= 10 {
    //                print("温度变化不大 可以调动")
    //            }
    //        }
    //        temperatureChange = {[weak self] newTempearture in
    //        //函数中又引用了self 造成了循环引用
    //            if abs(newTempearture - self!.temperature) >= 10 {
    //                print("温度变化太大")
    //            }
    //            else {
    //                self!.temperature = newTempearture
    //                print("这个不错")
    //            }
    //        }
                    temperatureChange = {[unowned self] newTempearture in
                    //函数中又引用了self 造成了循环引用
                        if abs(newTempearture - self.temperature) >= 10 {
                            print("温度变化太大")
                        }
                        else {
                            self.temperature = newTempearture
                            print("这个不错")
                        }
                    }
            
        }
        deinit {
            print("Smart 被销毁了")
        }
        
    }
    
    var airCon:SmartAirConditioner? = SmartAirConditioner()
    airCon?.temperature
    airCon?.temperatureChange(100)
    airCon?.temperatureChange(24)
    airCon = nil
  • 相关阅读:
    精通正则表达式(JavaScript)
    Go知识点记录
    多线程揭秘
    Python test
    ELinq+T4模版引擎制作多文件实体代码生成器
    浏览器内核
    MongoDb的增删改查
    LINQ执行表达式
    ASP.NET MVC3 读书笔记四(数据注解和验证)
    C#默认以管理员身份运行程序
  • 原文地址:https://www.cnblogs.com/huanying2000/p/6428170.html
Copyright © 2020-2023  润新知