如何在添加到NavigationController时释放ViewController对象?

时间:2013-04-16 05:06:16

标签: ios uinavigationcontroller release

首先,我已将我的ViewController添加到NavigationController,就像这样,

SecondViewController *viewControllerObj = [[SecondViewController alloc] init];
[self.navigationController pushViewController:viewControllerObj animated:YES];
[viewControllerObj release];`

但是这会导致崩溃,当我按下导航栏中的按钮后,它会推送到SecondViewController。所以我在.h文件中创建SecondViewController对象作为属性并释放 像这样的dealloc中的viewControllerObj,

现在我将我的ViewController添加到NavigationController,就像这样,

<。>在.h文件中,

@property (nonatomic,retain) SecondViewController *viewControllerObj;
<。>在.m文件中,

self.viewControllerObj = [[SecondViewController alloc] init];
[self.navigationController pushViewController:self.viewControllerObj animated:YES];

[_viewControllerObj release]; // in dealloc method

当我分析我的项目时,这显示 viewControllerObj 上的潜在泄漏,所以我修改了我的代码,

SecondViewController *temp =  [[SecondViewController alloc] init];
self.viewControllerObj = temp;
[temp release];
[self.navigationController pushViewController:self.viewControllerObj animated:YES];

现在我清除了潜在泄漏

但是我不知道这是否正确,是不是每个viewController对象都需要声明为Property并在dealloc发布????

1 个答案:

答案 0 :(得分:0)

  

就正确性而言,您始终可以使用autorelease而不是a   发布。自动释放是一种延迟释放。它将对象安排到   稍后会发布。

来自Link

因此,与第一个代码一起使用自动释放而不是发布消息。

SecondViewController *viewControllerObj = [[[SecondViewController alloc] init] autorelease];
[self.navigationController pushViewController:viewControllerObj animated:YES];
  

autorelease:在当前自动释放池块的末尾减少接收者的保留计数。

     

发布:减少接收者的引用计数。 (需要)。您只能实现此方法来定义自己的方法   参考计数方案。这样的实现不应该调用   继承方法;也就是说,它们不应包含发布消息   超级。

Advanced Memory Management Programming Guide

相关问题