自动释放与释放 [英] Autorelease vs. Release

查看:145
本文介绍了自动释放与释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于这两种情况,哪种代码是最佳做法,为什么?

Given the two scenarios, which code is best practice and why?

自动释放

loginButton = [[[UIBarButtonItem alloc] initWithTitle:@"Login" 
                                                style:UIBarButtonItemStylePlain 
                                                target:self 
                                                action:@selector(loginButtonClicked:)]
                                                autorelease];
self.navigationItem.rightBarButtonItem = loginButton;

/ strong>

Release

loginButton = [[UIBarButtonItem alloc] initWithTitle:@"Login" 
                                                style:UIBarButtonItemStylePlain 
                                                target:self 
                                                action:@selector(loginButtonClicked:)];
self.navigationItem.rightBarButtonItem = loginButton;
[loginButton release];


推荐答案

似乎有一个耻辱反对使用autorelease喜欢尽可能释放),这就是为什么我通常去第二条路线。但是因为你不在这里,释放现在与autoreleasing以后将有完全相同的效果(因为另一个对象保留loginButton,它不会是dealloc()ed)。

There seems to be a stigma against using autorelease (i.e. prefer to release whenever possible), which is why I typically go the second route. But since you're not in a loop here, releasing now vs. autoreleasing later will have exactly the same effect (since another object has retained loginButton, it won't be dealloc()ed).

但我应该指出,我的大部分内存泄漏是由忘记添加发布行引起的,所以它可能会更好地立即解决自动释放。

But I should point out that most of my memory leaks are caused by forgetting to add the release line, so it would probably be better to just tack on the autorelease right away.

这篇关于自动释放与释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆