[英]Does an iOS app's app delegate need to retain the UIWindow?
In the Xcode templates for iOS apps such as the 'View Based Application', a MainWindow nib is created with contains three top-level objects: The App Delegate, the Window, and the main View Controller. App Delegate 為 window 和視圖 controller 定義了retain
出口/訪問器。 我不明白為什么 App Delegate 需要保留這些對象,因為它們已經是 nib 中的頂級對象,因此應該由 UIApplication 保留。 檢查這些對象的retainCount
確實顯示1
表示應用程序委托, 2
表示 window 並查看 controller。 我可以/應該將這些更改為assign
嗎?
我知道這是一件很挑剔的事情,但我希望理解這樣做的原因將提高我對 iOS 中的 memory 管理的整體理解。
iOS 中的分配很棘手,我使用@property(非原子,保留)的插座。 與 Mac OS 不同,在 iOS 中連接到 XIB 對象的出口不會自動保留和 memory 管理,這可能會隨着 iOS 5 而改變,但不太可能。
這樣做的理由是,您可以在 - (void)viewDidUnload 中釋放任何視圖對象,並刪除您不需要的任何視圖,或者可以在 -(void)viewWillAppear 上重新初始化。 但表面上,目標是讓您控制收集的內容和不收集的內容。
我的模式是只為它們聲明正常的 cocoa 訪問器,就像我對任何其他屬性一樣,並在 viewDidUnload 中將它們設置為 nil
- (void)viewDidUnload
{
[super viewDidUnload];
self.buttonOne = nil;
self.buttonTwo = nil;
self.buttonThree = nil;
self.buttonFour = nil;
self.buttonFive = nil;
self.buttonSix = nil;
self.lineWidthSlider = nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
你是對的,但是,保留 window 並沒有多大意義,但對於一致性恕我直言是有意義的。 如此冗長的說法是,根據我的經驗,應用程序委托確實需要保留 UIWindow,或者它可以在 memory 掃描中收集並導致一些隨機崩潰。
看來應用程序委托確實需要保留window
UIWindow。
新 Xcode 項目中應用程序委托的默認實現包括:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
如果您刪除window
屬性並改為使用局部變量,應用程序將啟動到黑屏。
Xcode 也會記錄錯誤:
[應用] 如果要使用主 storyboard 文件,應用程序委托必須實現 window 屬性。
如果要使用主 storyboard 文件 swift,應用程序委托必須實現 window 屬性
將window
屬性設置為weak
同樣會啟動黑屏。 Xcode 將 UIWindow 分配給屬性時顯示錯誤:
實例將立即被釋放,因為屬性“窗口”是“弱”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.