引用计数
import UIKit
class OnePerson {
let name: String
init(name: String) {
self.name = name
print("\(name) is being initialized")
}
deinit {
print("\(name) is being deinitialized")
}
}
var reference1: OnePerson?
var reference2: OnePerson?
var reference3: OnePerson?
reference1 = OnePerson(name: "Xiao Yao")
reference2 = reference1
reference3 = reference1
print("reference1 nil")
reference1 = nil
print("reference2 nil")
reference2 = nil
print("reference3 nil")
reference3 = nil
console log 如下
weak 防止循环强引用
import UIKit
// 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")
}
}
var john: Person?
var unit4A: Apartment?
john = Person(name: "Jhon Applesseed")
unit4A = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john
print("John nil")
john = nil
print("unit4A nil")
unit4A = nil
console log 如下
注意: Person 和Apartment 关系分析
unowned 关键字
import UIKit
// unowned 关键字
class Customer {
let name: String
var card: CreditCard?
init(name: String) {
self.name = name
}
deinit {
print("Customer \(name) is being deinitialized")
}
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
}
deinit {
print("Card #\(number) is being deinitialized")
}
}
var john: Customer?
john = Customer(name: "John Appleseed")
john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)
john = nil
console log 如下
注意: Customer 和 CreditCard 关系如下
unowned 例子
import UIKit
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
}
}
var country = Country(name: "China", capitalName: "BeiJing")
print("\(country.name)'s capital city is called \(country.capitalCity.name)")
console log 如下
避免闭包的循环强引用
//: Playground - noun: a place where people can play
import UIKit
// 避免闭包的循环强引用
class HTMLElement {
let name: String
let text: String?
lazy var asHTML: () -> String = {
[unowned self] in
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) is being deinitialized")
}
}
var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
print(paragraph!.asHTML())
paragraph = nil
console log 如下
注意: 分析如下