我有一个基于拆分视图控制器的应用程序。在详细视图控制器中,将其称为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的行,一切都很好,但是我泄漏了内存。如果我按原样离开该行,那么在内存警告的情况下,应用程序崩溃。
我该怎么办?
谢谢, 米哈伊
答案 0 :(得分:0)
我很想知道你发布detailViewController而不是secondVC的第一个代码块?因为你的secondVC没有在方法结束时发布。您应该在dealloc方法中释放detailViewController而不是SplitViewAppDelegate,因为它是拆分视图的根视图的一部分。
欢呼,希望它有所帮助。