Xcode 5.0 之後,專案預設就已經改為都使用ARC,要取消還得另外去設定,官方文件,用ARC可以節省很多的時間,的確。
Without ARC
官方文件,物件的 reference counting (retainCount) 決定何時物件將所佔的記憶體歸還給系統,當建立物件時,retainCount即為1,retain +1,加進到 array 或是UI元件時也 +1, release -1,如果 retainCount為0時,物件消失。
手動管理記憶體很麻煩,常常忘了在 dealloc中release,造成memory leakage (記憶體慢慢流失),或是殺過頭重複釋放物件 (整個程式crash),所以後來出現了 autorelease,只要記得將物件加入至autorelease pool,當pool被清掉時,在池中的每個物件 retainCount -1。
如果物件的取得不是以下的方式,那它已經之前都呼叫過autorelease,被放入池中了,和同伴一起開發程式時,應遵守回傳物件先autorelease,好有效地管理記憶體。
- alloc
- new
- copy
- mutableCopy
- __strong
- __unsafe_unretained
- __autoreleasing
Property attribute
- assign : 簡單的替換變數,通常用在基礎型別(非物件)。
- retain : 用在物件,retainCount +1,確保物件在程式運行時不會被清掉。
- strong :
- copy : 通常用在新資料為mutable,而原資料為immutable時,可以維持原資料。
With ARC
Variables
- __strong (預設) : 在物件還需要使用時,盡可能不被清理掉,當不需要時就回收。
- __weak : 當沒有strong references 指向它時,dealloc and automatically becomes nil,這是ARC新增的最重要的 qualifier 。
- __unsafe_unretained : 和__weak類似,只是沒有自動指向nil。
- __autoreleasing : 通常接受pass by reference的物件,並加入autorelease pool。
Property attribute
- assign : 等同於 __unsafe_unretained
- strong : (預設)等同於 __strong
- copy : 如上
- weak : 等同於 __weak
IBOutlet
習慣上設定為 weak,因為加到view上的這些元件,view已經指向它們,retainCount也自動加上1,如果設定為 strong,將形成 strong reference cycles,永遠殺不掉。至於最上層的物件,例如UIViewController's view outlet, or NSWindowController's window outlet則是 strong。