在swift开发中强引用和循环引用很容易发生的,针对这个情况swift使用了两个关键词作为破处这种循环引用的方式:weak unowned
A weak reference is a reference that does not keep a strong hold on the instance it refers to, and so does not stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle. You indicate a weak reference by placing the weak
keyword before a property or variable declaration.
下面是官方典型的Person与Department之间关系的strong引用的展示:
代码语言:javascript复制var str = "Hello, playground"
class Person {
var name: String
var department: Deparment?
init(name: String) {
self.name = name
}
deinit { print("(name) is being deinitialized") }
}
class Deparment {
let unit: String
init(unit: String) { self.unit = unit }
var tenant: Person?
deinit { print("Apartment (unit) is being deinitialized") }
}
var person:Person? = Person(name: "Jack")
var deparment: Deparment? = Deparment(unit: "IT")
person?.department = deparment
deparment?.tenant = person
person = nil
deparment = nil
对于这种情况下: Person和Department之间相互持有,形成一种相互引用的关系,当垃圾♻️时谁也不愿意放手……于是虽然实例的引用都被置为nil,但是无法回收而成为内存中的孤魂野鬼无法投胎再循环啦……
Because a weak reference does not keep a strong hold on the instance it refers to, it’s possible for that instance to be deallocated while the weak reference is still referring to it. Therefore, ARC automatically sets a weak reference to nil
when the instance that it refers to is deallocated. And, because weak references need to allow their value to be changed to nil
at runtime, they are always declared as variables, rather than constants, of an optional type.
红线处真是指出weak的原理:当实例的引用销毁时,ARC会自动将weak修饰的引用设置为nil
基于此可以将Person中的department设置为weak, 或者Department中的tenant设置为weak
代码语言:javascript复制class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
weak var tenant: Person?
deinit { print("Apartment (unit) is being deinitialized") }
}
修改之后我们看一下测试结果:
注意
在系统的垃圾回收机制中,对于在内存紧张是系统就会回收哪些weak引用的数据。因此,在ARC下,weak不实用于那些一旦移除strong引用就立即销毁的情况(weak指向的是在内存紧张才再系统被动执行下回收的)
Like a weak reference, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime. You indicate an unowned reference by placing the unowned
keyword before a property or variable declaration.
unowned与weak目的都是为了防止strong引用关系造成内存泄露,但是与weak不同的是unowned引用修饰实例通常是与宿主的声明周期相同或者滋生有一个比较长的声明周期
代码语言:javascript复制class Customer {
let name: String
var card: CreditCard?
init(name: String) {
self.name = name
}
deinit { print("(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") }
}
代码语言:javascript复制var john: Customer? = Customer(name: "John Appleseed")
john?.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)
john = nil
闭包中的循环引用