我在我的应用中使用navigationController。在我推动并弹出一个视图控制器3次后,我的应用程序因内存不足而崩溃。这是我的代码。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
HomePageVC *homePage = [[ViewController alloc] homePage = [[ViewController alloc] initWithNibName:@"MainView-iPad" bundle:nil];
navigationController = [[UINavigationController alloc] initWithRootViewController:homePage];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
return YES;
}
当用户按下按钮时,我将他发送到另一个视图控制器。
-(IBAction)showMap:(id)sender
{
MapViewController *mapViewController = Nil;
mapViewController = [[MapViewController alloc] initWithNibName:@"MapView-iPad" bundle:nil];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.navigationController pushViewController:mapViewController animated:YES];
}
当他想回到rootView Controller时,我做
-(IBAction)goBack:(id)sender
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.navigationController popToRootViewControllerAnimated:YES];
}
现在这几次之后,逐渐调用didReceiveLowMemory并且应用程序崩溃了。
为了进行更多调试,我在循环中打印了内存使用情况。
-(void) report_memory {
struct task_basic_info info;
mach_msg_type_number_t sizeM = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&info,
&sizeM);
if( kerr == KERN_SUCCESS ) {
NSLog(@"Memory usage: %.4lf MB", info.resident_size/1000000.0);
} else {
NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
}
}
输出
When the app Launches : Memory usage: 137.8263 MB
After showMap First Time : Memory usage: 206.2172 MB
Gone Back Home : Memory usage: 223.6580 MB ==> MapVC didn't release
After showMap Second Time: Memory usage: 227.2172 MB
Press Go Back Home : Memory usage: 250.2172 MB ==> MapVC didn't release
After showMap Third Time : App Crashes
我的lowMemory写成
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
NSLog(@"Got Low Memory From %@",[self class]);
}
为了增加更多惊喜,我从HomePageVC和MapVC获得了低内存警告。如果我得到了MapVC,我是如何从中获得lowMemory的呢?为什么MapVC消耗的内存没有被释放?我正在使用ARC。
答案 0 :(得分:4)
我的代码中遇到了同样的问题(使用ARC),在调用popToRootViewControllerAnimated后我的UIViewController没有被释放:
我的错误原因是由于UIViewController中的NSTimer。我试图在dealloc中使计时器无效,但因为我的NSTimer使用了target:self(即保留指向我的UIViewController的指针)dealloc从未被调用过。
要解决此问题,我在viewWillDisappear中使计时器无效。
答案 1 :(得分:1)
看起来iOS除非需要,否则不会释放内存。我添加了一些代码来分配大量内存。弹出视图控制器时,内存从未发布。但是当调用didReceiveMemorywarning时,实际上我得到了回忆。我通过本练习学到的另一件事是,当它不是来自apple tutorial here的活动窗口时,释放视图。
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
if ([self.view window] == nil)
self.view = nil;
}