【问题标题】:How to release the ViewController Object when added to NavigationController?添加到 NavigationController 时如何释放 ViewController 对象?
【发布时间】:2013-04-16 05:06:15
【问题描述】:

首先我像这样将我的 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时释放????

【问题讨论】:

    标签: ios uinavigationcontroller release


    【解决方案1】:

    就正确性而言,您始终可以使用自动释放而不是 释放。自动释放是延迟释放。它将对象调度到 稍后收到它的发布。

    来自Link

    因此,不要使用发布消息,而是在您的第一个代码中使用自动发布。

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

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

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

    Advanced Memory Management Programming Guide

    【讨论】:

    • 确保你不应该过度释放对象删除释放语句,如果有代码或dealloc方法。
    • 检查了@Bhargavi
    • 好的,除了发布案例之外,检查您的 .xib 名称并确保它是准确的“SecondViewController”,如果不是这样,那么您必须使用 SecondViewController * viewControllerObj = [[SecondViewController alloc] initWithNibName:@"" bundle:[NSBundle mainBundle]];
    • 我有与“SecondViewController”同名的xib文件,在我的情况下,导航控制器显示secondviewcontroller但是当我点击返回按钮时它会崩溃,为此我将第二个viewcontroller声明为属性并在dealloc中释放它工作正常。但我不知道这是否是正确的程序???
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多