ARC 記憶體管理 weak 和 unowned

Zhi-Hong Lin
2 min readMar 5, 2019

--

雖然在 Swift 中,有 ARC(Automatic Reference Counting) 的機制在控管記憶體,但我們還是要注意可能會造成 Reference Cycle 的情況發生,下面這段程式碼呈現造成 Reference Cycle 的狀況。

雙方都是 strong reference ,互相持有對方的物件,即使將實例設成 nil,但物件的記憶體並不會被釋放掉,最終就會造成 Reference Cycle。

在 Swift 裡防止 Reference Cycle — weak

這裡我們將 Food 物件裡的 var cat 前面加上了 weak,來打破 strong reference 循環,當實例要被釋放時,ARC 就會自動設定 weak reference 為 nil

在 Swift 裡防止 Reference Cycle — unowned

unowned reference 也能夠打破 strong reference 循環,但 ARC 不會將 unowned reference 的數值設為 nil ,如果你在實例已經被釋放後,嘗試取得一個 unowned reference 的數值,運行就會出錯。

Strong、Weak 和 Unowned 的差別

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response