Skip to main content

[Swift3] weak 與 unowned 關鍵字

雖然在 Swift 中看起來"很像"是不需要煩惱內存管理的問題,不過實際上它還是遵循著自動引用計數 (ARC) 的規則,當一個物件沒有被其他對象引用時會自動被銷毀,如果三魂七魄沒有完全回位的話,就會有個靈體留在現世的空間裡,最經典的範例如下:

閉包(Closure)引用


classClassA {

typealias Complete = ()->()

var name : String
var onComplete : Complete?

init(_ name: String){
self.name = name
print("Hello I am \(self.name)")

onComplete = {
print("\(self.name): onComplete!") // --> 閉包引用 self, 計數 + 1
}
}

deinit {
print("deinit: \(self.name)")
}
}

var a : ClassA? = ClassA("A") // --> 引用計數 + 1
a = nil // 2-1 = 1 還剩下 1 所以沒辦法銷毀

---output-------
Hello I am A

由於這邊的 onComplete 宣告為 Optional, 正確的做法要連同 onComplete 一起刪除才可以被回收,若不是 Optional 則會進入無法回收狀態:

var b : ClassA? = ClassA("B")
b?.onComplete = nil // --> 還好是 Optional 可以設成 nil 計數 - 1
b = nil // 計數 = 0 所以被回收

---output-------
Hello I am B
deinit: B

但是做人不需要煩惱太多,這時候就出動 unowned 關鍵字讓物件可以順利被回收:

onComplete = { [unowned self] in
print("\(self.name): onComplete!") // --> 沒有強制持有 self
}

---output-------
Hello I am A
deinit: A

不過眼尖的朋友應該會發現,在網路分享的教學文章內,也常看到有人使用 [weak self] 到底與 [unowned self] 最大的差別是什麼?

無主的 (unowned) 與 虛體 (weak)

直接翻成中文應該就很比較容易區分了吧?unowned 通常都用於該實體不會比引用閉包或持有它的物件更早被刪除如:self 或 parent,所以一般來說,用於 self 直接採用 [unowned self] 寫法比較直覺。

onComplete = { [unowned self] in
print("\(self.name): onComplete!") // --> unowned self 計數虛的
}

但是人生就是不怕一萬只怕萬一,誰知道那天 self 會不會提早被 release?所以基於安全的情況下就會使用 [weak self]。

onComplete = { [weak self] in
//這邊的 self 是 Optional 所以需要寫成 self?.xxx
print("\(self?.name ?? "nil"): onComplete!")
}
//建議寫法:
onComplete = { [weak self] in
if let strongSelf = self {
print("\(strongSelf.name): onComplete!")
}
}

所以當你無法確定使用哪個的話,直接採用 [weak self] 就可以囉!

循環引用

另外一種需要考慮加上 weak 或 unowned 關鍵字的情況就是循環引用。循環引用會讓程式 呈現一種「你中有我,我中有你」的境界:

class User {

var name : String
var firend: User?

init(_ name: String){
self.name = name
print("Hello I am \(self.name)")
}

func makeFriend(_ user: User) {
firend = user
print("\(self.name)'s new friend is \(user.name)")
}

deinit {
print("deinit: \(self.name)")
}
}

var A: User? = User("A")
var B: User? = User("B")

A?.makeFriend(B!)
B?.makeFriend(A!)

A = nil
//理論上 A 掛了應該印不出來會是 nil,
//但是因為沒有正確消除引用計數,所以 A 還是存在在 B 的心裡(朋友啊!我懷念你)
print(B?.firend!)
B = nil // 兩個都掛了但是還有魂體沒有回收而成為地縛靈

---output----------
Hello I am A
Hello I am B
A's new friend is B
B's new friend is A
Optional(User)

上面情況真的要能回收就是得在 A = nil 那段下面加上:

B?.firend = nil // A 被回收了
B = nil // 所以 B 也可以順利回收

---output----------
Hello I am A
Hello I am B
A's new friend is B
B's new friend is A
deinit: A
deinit: B

同理,不想要煩惱太多就是採用 weak 關鍵字指定 friend:

class User {

var name : String
weak var firend: User?

init(_ name: String){
self.name = name
print("Hello I am \(self.name)")
}

func makeFriend(_ user: User) {
firend = user
print("\(self.name)'s new friend is \(user.name)")
}

deinit {
print("deinit: \(self.name)")
}
}

var A: User? = User("A")
var B: User? = User("B")

A?.makeFriend(B!)
B?.makeFriend(A!)

A = nil
print(B?.firend) // 朋友是虛的,不見就讓它隨風去吧...

---output----------
Hello I am A
Hello I am B
A's new friend is B
B's new friend is A
deinit: A
nil

總結

  • unowned: 使用於目標實體不會在執行閉包前或者是比引用它的物件還要早被回收的狀態下。
  • weak: 剩下的情況都可以適用。
  • 例外: 如果在 root ViewController 或 Singleton class 絕對不會被回收情況下,閉包引用就不需要考慮是 weak 還是 unowned 了,因為寫不寫不是很大的問題。

Comments

  1. I am regular reader, how are you everybody? This post posted at this website is actually pleasant. paypal login

    ReplyDelete
  2. A 30-year fixed-rate mortgage is among the most common type of mortgage. books

    ReplyDelete
  3. A 30-year fixed-rate mortgage is easily the most common type of mortgage. textbooks

    ReplyDelete
  4. Just plug within your starting amount and just how long you prefer to save, then experiment with the rate of return, annual contributions, frequency and interest to determine simply how much money you possibly can make. mortgage calculator Refinancing your mortgage lets you change the term of the current mortgage. mortgage payment calculator canada

    ReplyDelete

Post a Comment

Popular posts from this blog

PureMVC 我也會 [6]

Mediator ViewComponents 與 pureMVC 架構的中介 監聽並反應 View Component 發出的 Event 可以發送與接收 Notification 儘量少操作 Proxy 公開方法,多用 sendNotification... Mediator design pattern 要多認識這個 Mediator 設計模式的話,請自行看連結說明啊! 簡單來講,假使有一個 View 裡面有好幾個 MovieClip 組成,而這些 MovieClip 會互相影響對方...這個情況在 Flash 中,通常都會變成下圖: MovieClip 直接控制其他 MovieClip 搞到整個關係很複雜...換一個元件簡直是災難。 加入 Mediator 後,示意圖就會變成: 這樣,所有的 MovieClip 都透過 Mediator 來跟其他 MovieClip 溝通,當某一個 MovieClip 替換成別的元件,這時候也只需要修改 Mediator 中的引用即可,是不是變得很乾淨?如果同一組 MovieClip 有另外一個操作模式,也只需要替換掉 Mediator 即可!天下太平啊~~~ 而 PureMVC 中就是利用 Mediator class 為與前端 ViewComponent 的中介,這樣可以切開 ViewComponent 與 PureMVC framework 的關係,不管你前端介面使用 Flash or Flex 製作都跟程式核心無關。 所以 ViewComponent 製作時只需要兩個原則,一把所有的請求都以 Event 送出由 Mediator 處理,二提供公開方法, Mediator 只需要監聽 View 的 Event,將收到的資訊透過公開方法喂進 ViewComponent 即可。 如在 ViewComponent 中: public function setList( result:Object ):void{ list.dataProvider = result as ArrayCollection; } //然後在按下取得資料的按鈕 Click action 寫上: dispatchEvent( new Event( "GET_LIST" )); 新建 Mediator 的時候一樣有幾個重點方...