【发布时间】:2014-04-20 00:12:56
【问题描述】:
我有一个UINavigationController,并且一旦另一个位于堆栈顶部的UIViewController,我就会尝试从内存中释放。我将UINavigationController 的viewControllers 属性分配给新的UIViewController,然后弹出它。这样我总是只有一个 UIViewController 在堆栈中。但是,每次我创建一个新的UIViewController 时,内存都会不断增加。调用了 Dealloc,但内存使用量保持不变。
您可以下载示例项目HERE
FirstViewController.h
#import "SecondViewController.h"
@interface FirstViewController : UIViewController
-(IBAction)goToSecond:(id)sender;
@end
FirstViewController.m
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", self.navigationController.viewControllers);
}
-(void)goToSecond:(id)sender{
SecondViewController *secondVC = [[SecondViewController alloc]init];
[self.navigationController setViewControllers:@[secondVC]];
[self.navigationController popViewControllerAnimated:NO];
}
-(void)dealloc{
NSLog(@"FirstVC dealloc");
}
@end
SecondViewController.h
#import "FirstViewController.h"
@interface SecondViewController : UIViewController
-(IBAction)goToFirst:(id)sender;
@end
SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", self.navigationController.viewControllers);
}
-(void)goToFirst:(id)sender{
FirstViewController *firstVC = [[FirstViewController alloc]init];
[self.navigationController setViewControllers:@[firstVC]];
[self.navigationController popViewControllerAnimated:NO];
}
-(void)dealloc{
NSLog(@"SecondVC dealloc");
}
@end
【问题讨论】:
-
你为什么要这样做? UINavigation 栏会跟踪您的内存并按时释放正确的视图,如果您希望始终拥有一个视图控制器,请不要使用导航控制器。甚至不使用方舟,这样你就可以释放它。但我不建议你这样做。
-
如果您想返回,那么应该首选简单的
pushViewController和popViewController。 -
@PiratM,你会建议什么来代替
UINavigationController?我一次只需要一个ViewController。 -
@YasKuraishi 我试过
push和pop但ViewController消耗的内存保持不变。您可以在示例项目中查看它。您可以看到创建SecondViewController时内存图是如何上升的,但是当它被弹出时,内存并没有减少。 -
@guardabrazo 您的应用中有多少个视图控制器?您是否需要所有这些“后退”功能?您需要释放它们的内存使用情况是什么?如果您只有几个 ViewContoller,您可以构建自己的假导航控制器。只有一个看起来完全一样的简单视图,但使用了 PresentView 控制器和dismissViewController。
标签: ios objective-c memory-management uiviewcontroller uinavigationcontroller