Skip to content

Latest commit

 

History

History
39 lines (36 loc) · 1.04 KB

File metadata and controls

39 lines (36 loc) · 1.04 KB

1.如何解决循环引用

一般循环引用分为 Strong Reference Cycles Between Class Instances 和 Strong Reference Cycles for Closures 一、Strong Reference Cycles Between Class Instances 用weak 类似OC中的 __weak

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { print("\(name) is being deinitialized") }
}
 
class Apartment {
    let unit: String
    init(unit: String) { self.unit = unit }
    weak var tenant: Person?
    deinit { print("Apartment \(unit) is being deinitialized") }
}

二、Strong Reference Cycles for Closures 用unowned 类似OC中的__block

class Country {
    let name: String
    var 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
    }
}