我想加載一個新的視圖到現有的視圖控制器,但我想從一個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
謝謝,我還沒有弄清楚爲什麼保留數每次跳躍3次,但是我覺得這很麻煩,我只是試着重構一些東西來完全避免這個問題。我希望我有足夠的聲望在下面回答Hikaru的回答,同樣也有幫助。 – niels 2009-07-15 05:36:49