強引用循環(huán)
兩個引用類型實例之間相互引用。
解決方式
實例之間的:
- 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?
}
-
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 } }
-
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):
在定義閉包時仰迁,添加一個列表甸昏,用來捕獲產生循環(huán)的引用。
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak someInstance] (index: Int, stringToProcess: String) -> String in
// closure body goes here
}