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

[作品]Flex 3.4 + PureMVC 的企業級 RIA 應用

認識 Erin 的人都知道, Erin 最懶得寫作品集相關的文章,但是這個案子比較有趣,所以特別提出來聊一下囉! 廚櫃業某公司內部軟體,目前系統尚在 Beta 階段,所以下面圖片皆有模糊化處理。 [可擴充功能面板首頁,後台皆包含在管理系統內(有 iPhone 的 fu)] 這個案子是幫一家傳統公司做的專用軟體線上化,想要開發企業級 RIA 想當然爾就是使用 Flex 來處理囉! 整個案子前端是以 Flex SDK 3.4 + Flex Builder3, PureMVC MultiCore for AS3 , Utility - AS3 StateMachine 以及先前 Erin 所發表的 WidgetsConsole 來處理整個系統的轉換。 整個系統包含前後台共七大系統,分別是:估價,客戶,店面管理,貨品上架,會員管理,分店系統以及權限系統。超級管理員可以利用權限系統分別開出不同職級的權限,然後使用者透過同一入口,依照權限區分,畫面會顯示不同的功能。整個系統最複雜的部份當然是估價系統,由於櫥櫃的建立是透過選擇資料即時演算出來,更何況櫥櫃類的 BOM 表階層是怪物般的可怕...所以在 DB 的建置與前端資料整合的部分著實費了我們一番苦心。 [櫥櫃 BOM 表編輯視窗及櫥櫃 BOM 單物件材質指定] 此外,在 UI 設計上也特別花了一些心思。本案子 Target User 是管理者、店長與公司旗下的業務群,此公司成員年齡約 30-60 歲,皆為一般電腦使用者,所以 UI 設計及操作 Flow 必須比一般線上 RIA 更加友善,才能幫助縮減公司的人事教育花費。如放大整個系統的標準字 size;新增資料時不能碰的快速鍵會鎖定;產品類縮圖雙點擊即可觀看放大圖;操作 flow 皆以左上至右下結束以及利用畫面引導使用者操作都是一些設計上的巧思。 [新增估價單] [簡單易用的業務員用客戶系統] 此外這個專案在實作 PureMVC 過程當然是相當的快樂,因為它的彈性與權職切分實在太令人滿意了!不管是擴充性,Rich Data 管理又或者除錯都非常的容易。當然本人早就已經是 PureMVC 的忠實粉絲了...=P 快來加入 Flex + PureMVC 的行列吧~~ 結果這篇到最後變成 PureMVC 的勸進文...XD