[英]Reference counting of UIViewController
當我執行以下步驟時,我只是遇到了一種奇怪的行為,
視圖顯示正確。 該視圖有一個按鈕,當我單擊該按鈕時,它會崩潰,並顯示EXEC_BAD-ACCESS
。 經過一段時間的調試后,發現視圖控制器實例已釋放,並且由於該控制器不存在,因此未觸發按鈕單擊事件。
當我將視圖控制器的聲明移到類級別時,它開始工作。 我覺得如果視圖控制器的視圖在屏幕上,則不應保留視圖控制器實例。
有什么想法嗎?
一些代碼指針。
class SomeViewController:UIViewController{
var workingVC:SomeVC?
func crashingMethod()
{
let vc:SomeVC = SomeVC(nibName:"SomeVC", bundle:NSBundle.mainBundle())
let delegate:AppDelegate = UIApplication.sharedApplication().delegate
let applWindow:UIWindow = delegate.window!
applWindow.addSubview(vc.view)
}
func workingMethod()
{
self.workingVC = SomeVC(nibName:"SomeVC", bundle:NSBundle.mainBundle())
let delegate:AppDelegate = UIApplication.sharedApplication().delegate
let applWindow:UIWindow = delegate.window!
applWindow.addSubview(self.workingVC!.view)
}
}
當您創建這樣的對象時
let vc:SomeVC = SomeVC(nibName:"SomeVC", bundle:NSBundle.mainBundle())
對象生存期等於創建對象的范圍。 范圍結束時,ARC釋放該對象和所有關聯的對象。
但是,當您在類級別添加它時,此對象的生存期等於owner(SomeViewController)的生存期。 因此,僅在所有者釋放時才釋放。
你清楚嗎? 您也可以在Apple文檔的“內存管理”部分中閱讀有關此內容的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.