2009-07-10 85 views
1

我想加載一個新的視圖到現有的視圖控制器,但我想從一個xib文件加載該視圖。我的計劃是創建第二個viewController(viewController1在下面的代碼中),然後保留其視圖,並釋放我剛剛創建的viewController。我希望viewController會被釋放,並且視圖會停留,但這似乎並沒有發生。我可以在發佈ViewController時保留視圖嗎?

問題1:如果viewcontroller得到處理,無論視圖的保留計數是什麼,它的相關視圖是否得到處理?在下面的示例代碼中,您可以看到該視圖在突然消失之前的保留計數爲13。

問題2:爲什麼保留視圖的retainCount增加3?

PageViewController *viewController1 = [[PageViewController alloc] initWithNibName:@"Page1" bundle:nil]; 
[viewController1.view setUserInteractionEnabled:YES]; 

NSLog (@"vc retain count: %d", [viewController1 retainCount]); //count=1 
NSLog (@"vc view retain count: %d", [viewController1.view retainCount]); //count=4 

self.currentPageView=viewController1.view; 

NSLog (@"vc retain count: %d", [viewController1 retainCount]); //count=1 
NSLog (@"vc view retain count: %d", [viewController1.view retainCount]); //count=7 


[viewController1.view retain]; 

NSLog (@"vc retain count: %d", [viewController1 retainCount]); //count=1 
NSLog (@"vc view retain count: %d", [viewController1.view retainCount]); //count=10 

[self.view addSubview:viewController1.view]; 

NSLog (@"vc retain count: %d", [viewController1 retainCount]); //count=1 
NSLog (@"vc view retain count: %d", [viewController1.view retainCount]); //count=13 

[viewController1 release]; 

NSLog (@"vc view retain count: %d", [viewController1.view retainCount]); 
//objc[3237]: FREED(id): message view sent to freed object=0x538ce0 

回答

1

你得到的不是告訴您觀點已經釋放了「發送到釋放對象信息」的錯誤,那就是viewController1已被釋放,因而你得到的發送「查看」消息時出錯。 (請記住,在Objective C中,每個屬性訪問都會發送一條消息......)

但我不確定爲什麼視圖的保留數每次跳躍3次。

+0

謝謝,我還沒有弄清楚爲什麼保留數每次跳躍3次,但是我覺得這很麻煩,我只是試着重構一些東西來完全避免這個問題。我希望我有足夠的聲望在下面回答Hikaru的回答,同樣也有幫助。 – niels 2009-07-15 05:36:49

1

這可能幫助:

[[NSBundle mainBundle] loadNibNamed:@"Page1" owner:self options:nil]; 

其中自是現有的viewController。

1

此行是沒有意義的

self.currentPageView=viewController1.view;

在viewController1的觀點並未建立起來,因爲該控制器的方法的loadView不叫

雖然可以添加新的子視圖到viewController.view因爲「魔術」允許您將對象添加到尚未構建的視圖。

它並沒有改變這個事實 - 當時viewController.view不存在。

注:所有controller.view建在viewDidLoad中/的loadView方法,並viewDidLoad中/的loadView不會叫,直到它會顯示(如:pushController)

通常我不靠,因爲保留櫃檯它不可靠。

相關問題