2013-04-16 19 views
1

首先我加了我的ViewController以NavigationController这样,如何在添加到NavigationController时释放ViewController对象?

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

但这创建崩溃,当我在导航栏上按后退按钮后,被推到SecondViewController。所以我创建SecondViewController对象在.H文件属性,并以这样的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中释放?

回答

0

就正确性而言,您始终可以使用autorelease而不是 版本。自动释放是延迟释放。它安排对象 在稍后收到它的发布。

Link

因此,不要使用第一个代码释放消息使用自动释放。

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

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

版本:递减接收器的引用计数。 (需要)。您只能实现这种方法来定义自己的 引用计数方案。这种实现不应该调用继承的方法;也就是说,他们不应该在超级版本中包含发布消息 。

Advanced Memory Management Programming Guide

+0

即使我试图与自动释放不起作用 –

+0

确保你不应该在发布对象中删除发布声明,如果任何代码或dealloc方法。 –

+0

检查也@Bhargavi –

相关问题