在 iPhone101.pdf 第 30 頁,關於 File's Owner 有這麼一段描述:
In a nib file, in contrast to the other objects you add to the interface, the File's Owner object is not created when the nib file is loaded. It represents the object set to be the owner in the method that loads the nib file—in this case, loadNibNamed:owner:options:. In your application, the File's Owner will be the instance of MyViewController.
意思是:nib 檔中的大部分物件,都是在該檔案被載入時才建立的;只有 File's Owner 例外,它不是被建立出來的,而是「載入這個 nib 檔的那個方法」所指定的 owner——在這裡就是 loadNibNamed:owner:options: 的 owner 參數。在這個範例 App 中,File's Owner 是 MyViewController 的一個實例。
我的理解是:File's Owner 指的是這個 nib 檔的擁有者,它需要負責建立與銷毀檔案中的物件。至於 loadNibNamed:owner:options: 這個方法我沒有找到,推測是在框架內部。
這個設計其實很關鍵。如果 File's Owner 也要由 nib 檔自己建立,那就會變成「誰來載入」的無限遞迴問題。把 owner 交由外部傳入,nib 檔就能重用——同一個介面檔可以被不同的控制器載入,這正是 iPhone101 範例裡 MyViewController 的角色。
The Application Loads the Main Nib File.大多數 Xcode 的 App 專案範本都預先配置好了一個 main nib 檔,你只要在 Interface Builder 裡修改它、再 build 即可。在啟動時,App 的預設組態資料會告訴 application 物件去哪裡找這個 nib 檔。在 AppKit 與 UIKit 系的 App 中,這份組態位於 App 的 Info.plist:App 首次載入時,啟動流程會去 Info.plist 找 NSMainNibFile 這個 key;找到後,再到 App bundle 中尋找名稱(含或不含副檔名)與該 key 值相符的 nib 檔並將它載入。
Each View Controller Manages its Own Nib File.UIViewController(iOS)與 NSViewController(Mac OS X)支援自動載入各自關聯的 nib 檔。若你在建立 view controller 時指定了 nib 檔,那麼當你第一次存取該 controller 的 view 屬性時,nib 檔就會被自動載入;controller 與 nib 物件之間的連線也會自動建立。在 iOS 中,view 真正載入並顯示於螢幕上時,UIViewController 還會收到額外的通知。此外為了更好地管理記憶體,UIViewController 也會在記憶體吃緊時適時卸載它的 nib 檔。
更多用法可參考《View Controller Programming Guide for iOS》。
把這兩段放在一起看,結論就很清楚:main nib 檔由 application 處理,其餘的 nib 檔由各個 view controller 自行管理。
順帶一提,「記憶體吃緊時卸載 view」這個機制在後續的 iOS 版本中已被調整,但「誰載入、誰負責」的責任歸屬原則並沒有改變,理解它對排查接收到 memory warning 後的行為很有幫助。
摘自 pingjiang2003的專欄