如何在pushviewcontroller之后释放ViewController

时间:2012-09-21 08:00:17

标签: iphone memory-management uiimageview

我有2个视图,名为viewcontroller1,viewcontroller2。每个viewcontroller都加载了大约3张图片(在XIB中加载),当我尝试使用[self.navigationcontroller pushviewcontroller]时,将view1推送到view2,内存无法释放。(我想知道它无法释放viewcontrller1或者无法释放uiimageview )我的代码的任何错误?

viewcontroller1代码就像这样:

viewcontroller1.h

@interface ViewController : UIViewController
@property(strong,nonatomic)IBOutlet UIImageView *mainImageView;
@property(strong,nonatomic)IBOutlet UIImageView *topwallImageView;
@property(strong,nonatomic)IBOutlet UIImageView *buttonImageView;

viewcontroller1.m

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
self.mainImageView = nil;
self.topwallImageView = nil;
self.buttonImageView = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
}

-(void)dealloc
{
[mainImageView release];
[topwallImageView   release];
[buttonImageView release];
[super dealloc];
}

-(IBAction)main2ViewController:(id)sender
{
Main2ViewController *main2ViewController =[[Main2ViewController alloc]initWithNibName:@"Main2ViewController" bundle:nil];
[self.navigationController pushViewController:main2ViewController animated:NO];
[main2ViewController release];
}

1 个答案:

答案 0 :(得分:0)

您必须在iOS中详细了解对象通信和内存管理

另请尝试使用ARC。在iOS 5 sdk中引入了自动引用计数(ARC),以使Objective-C程序员不必通过将内存管理作为编译器的工作来处理内存管理。

您可以使用this link

将项目转换为启用ARC

当viewcontroller2可见或推送 viewcontroller2 后,您无法发布 viewcontroller1 及其IBOutlet属性。因为您从viewcontroller1推送 viewcontroller2 viewcontroller1 是viewcontroller2的容器/父级。 viewcontroller2将不存在with viewcontroller1

关于IBOutlet imageview图像,您可以将其设置为nil .Eg: yourImageview.image = nil; 但是它不会释放IBOoutlet Imageview内存。

IBOutlet imageview将在调用viewcontroller1的发布方法时发布,因为您在viewcontroller1 dealloc方法中正确发布了它:)

关于 Main2ViewController 方法:您在代码中正确处理了内存

当你调用pushViewController时,它将保留默认推送的控制器。请注意,您不是所有者。它会在弹出控制器时自动释放。但是你必须释放分配的Main2ViewController。所以你的代码很好:)