Swift 中的强引用循环

强引用循环

两个引用类型实例之间相互引用。

解决方式

实例之间的:

  1. Weak 引用。适用于一方的引用可为 nil 的情形。
class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
}

class Apartment {
    let number: Int
    init(number: Int) { self.number = number }
    weak var tenant: Person?
}
  1. Unowned 引用。适用于一方的引用不能为 nil 的情形。

    class Customer {
        let name: String
        var card: CreditCard?
        init(name: String) {
            self.name = name
        }
    }
    
    class CreditCard {
        let number: UInt64
        unowned let customer: Customer
        init(number: UInt64, customer: Customer) {
            self.number = number
            self.customer = customer
        }
    }
    
  2. Unowned 引用和隐式解包的可选属性。适用于双方的引用都不能为 nil 的情形。

    class Country {
        let name: String
        let capitalCity: City!
        init(name: String, capitalName: String) {
            self.name = name
            self.capitalCity = City(name: capitalName, country: self)
        }
    }
    
    class City {
        let name: String
        unowned let country: Country
        init(name: String, country: Country) {
            self.name = name
            self.country = country
        }
    }
    

闭包的(Capture List):
在定义闭包时,添加一个列表,用来捕获产生循环的引用。

lazy var someClosure: (Int, String) -> String = {
    [unowned self, weak someInstance] (index: Int, stringToProcess: String) -> String in
    // closure body goes here
}

你可能感兴趣的:(Swift 中的强引用循环)