• 弱引用----weak、unowned


    weak var person: Person?
    unowned let person: Person
    unowned var person: Person

      weak: 必须为var,必须为可选性(一定得有'?')。对象释放后,weak指针会自动置为nil。

      unowned:不可以是可选性(一定不可以有'?')。对象释放后,unowned指针不会自动置为nil。

    class Person {
        
        var name: String
        var dog: Dog?
        
        init(name: String) {
            self.name = name
            print("person initializa")
        }
        
        deinit{
            print("person deinitialize")
        }
    }
    
    class Dog {
    
        var name: String
        weak var person: Person?
        
        init(name: String) {
            self.name = name
            print("dog initializa")
        }
        
        deinit{
            print("dog deinitialize")
        }
    }
    
    var person: Person? = Person(name: "Tom")
    var dog: Dog? = Dog(name: "Taidi")
    dog.person = person person
    = nil dog?.person // nil dog = nil
    class Person {
        
        var name: String
        var dog: Dog?
        
        init(name: String) {
            self.name = name
            print("person initializa")
        }
        
        deinit{
            print("person deinitialize")
        }
    }
    
    class Dog {
    
        var name: String
        unowned var person: Person
        
        init(name: String, person: Person) {
            self.name = name
            self.person = person
            print("dog initializa")
        }
        
        deinit{
            print("dog deinitialize")
        }
    }
    
    var person: Person? = Person(name: "Tom")
    var dog: Dog? = Dog(name: "Taidi", person: person!)
    
    person = nil
    dog?.person  // 会崩溃
    dog = nil
  • 相关阅读:
    Http请求头和相应头分析
    linux扩充容量经典篇
    Redis持久化以及其原理
    redis简单应用
    Python Requests库使用2:请求方法
    加快访问GitHub的速度
    GET和POST两种基本请求方法的区别
    Python Requests库介绍
    Python urllib、urllib2、urllib3用法及区别
    Django中操作cookie和session
  • 原文地址:https://www.cnblogs.com/muzijie/p/6612938.html
Copyright © 2020-2023  润新知