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 for Unity

幾個月前改用 Unity 開發遊戲,到目前的心得為:組件式開發真的是很便利,但是當組件數量多到一定程度時,結構上就有點可怕,常常在某 GameObject 上掛了組件後就忘了它的存在,雖然可以使用 Singleton design pattern 來製作主要的 Manager(本人對 Singleton 並不是很熱愛),程式還是會亂到一定程度,搜尋了一些 Unity with MVC 討論,一部分的人都對實作 MVC 不是很熱絡,也許是 Unity 特有的開發環境導致。 以前開發 Adobe Flex 專案最愛用的 MVC Framework 就是 PureMVC,即使後來有更方便的 MVC Framework 的也擋不住我對它的熱愛。Unity 是沒有所謂的全域 Root Scene,所有場景都是獨立,想要將 AS3 實作邏輯套用在 Unity 上將控制項都在 PureMVC 架構中實作是有點矯情多餘。如何保持 Unity 組件開發模式,導入 PureMVC 鬆綁主要邏輯,就是這次實驗的重點。 不清楚 PureMVC 的朋友們可以到這邊參觀一下: PureMVC 我也會 PureMVC C# Standard Framework on GitHub ViewComponent 與 Mediator 整合是首要工作: 由於 Unity 沒有全域 Root Scene,如果將 new Mediator( viewComponent ) 寫在 PureMVC 架構下,即使透過 GameObject.Find 找那個對應的 GameObject 就轉了九彎十八拐,寫起來一點都不愉快,尤其考慮到場景的轉換,兩個場景中相關 Mediator 的註冊與移除處理,何況對 Unity 組件來說,能不能被打包動態載入是件重要的事。綜合以上問題點,反向思考,改由 GameObject 掛載中介組件,在 OnEnable 與 OnDisable 通知 Facade 去註冊與移除其 Mediator,一來簡化為了實作 Meditaor 掛載 ViewComponent 而對 static class GameObject 的依賴,二來也不會對 Unity 組件開發模式有太大的影響。