我有一个基于分割视图控制器的应用程序。在详细信息视图控制器,称之为FirstViewController,当用户按下一个按钮,我更新了新的视图控制器的视图控制器,称之为SecondViewContorller,类似下面:释放细节视图控制器导致内存问题
- (void) buttonPressed:(id)sender {
UIViewController <SubstitutableDetailViewController> *detailViewController = nil;
SecondViewController *secondVC = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
...
detailViewController = secondVC;
MyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
UINavigationController *nav = (UINavigationController *)[delegate.splitViewController.viewControllers objectAtIndex: 0];
NSArray *viewControllers = [NSArray arrayWithObjects:nav, detailViewController, nil];
self.splitViewController.viewControllers = viewControllers;
...
[detailViewController release];
}
里面的SecondViewController,在某些时候,我们有:
MyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
UINavigationController *nav = (UINavigationController *)[delegate.splitViewController.viewControllers objectAtIndex: 0];
NSArray *array = nav.viewControllers;
// Retrieve the master view controller
MasterViewController *masterVC = [array objectAtIndex:[array count] - 1];
[masterVC selectRowManually:[NSIndexPath indexPathForRow:0 inSection:0]];
和selectRowManually里面我再次初始化FirstViewController:
UIViewController <SubstitutableDetailViewController> *detailViewController = nil;
if (rowNo == 0) {
FirstViewController *newDetailViewController = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
detailViewController = newDetailViewController;
}
...
UINavigationController *nav = (UINavigationController *)[delegate.splitViewController.viewControllers objectAtIndex: 0];
// Update the split view controller's view controllers array.
NSArray *viewControllers = [[NSArray alloc] initWithObjects:nav, detailViewController, nil];
delegate.splitViewController.viewControllers = viewControllers;
[viewControllers release];
...
[detailViewController release];
如果我模拟内存将在该时间点警告(在FirstViewController已经再次显示后),我得到一个
-[UIView _invalidateSubviewCache]: message sent to deallocated instance ...
与
#0 0x012dd057 in ___forwarding___
#1 0x012dcf22 in __forwarding_prep_0___
#2 0x00b49a55 in -[UIView dealloc]
#3 0x00bbe52a in -[UIViewController setView:]
#4 0x00bc0eec in -[UIViewController unloadViewForced:]
#5 0x00bbcb0a in -[UIViewController unloadViewIfReloadable]
#6 0x00bbc15b in -[UIViewController didReceiveMemoryWarning]
#7 0x0006aec7 in -[SecondViewController didReceiveMemoryWarning] at SecondViewController.m:385
...
,其中线385堆栈跟踪是
[super didReceiveMemoryWarning];
如果在SecondViewController的buttonPressed方法中,我注释了释放该行的位置detailViewContorller,一切正常,但我泄漏内存。如果我以这种方式离开该线路,那么如果出现内存警告,该应用会崩溃。
我该怎么办?
感谢, 米哈伊
感谢您的回答。 detailViewController对于该方法是本地的。在detailViewController = secondVC之后,两者都指向相同的SecondViewController对象,因此释放detailViewController或secondVC不应该有任何区别。 – 2011-01-26 16:13:04