之后自动释放或释放更好吗? [英] Is it better to autorelease or release right after?

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

问题描述

在很多情况下,人们会分配一个实例,并在将其分配给其他内容后立即释放它,并在内部保留它。

There are a lot of cases in which one would alloc an instance, and release it right after it's being assigned to something else, which retains it internally.

For例如,


UIView *view = [[UIView alloc] initWithFrame...];
[self addSubView:view];
[view release];

我听说有人建议我们选择自动发行,而不是立即发布。

I have heard people suggesting that we go with autorelease rather than release right after.

所以上面变成了:


UIView *view = [[[UIView alloc] initWithFrame...] autorelease];
[self addSubView:view];

这里的最佳做法是什么?优点和缺点?

What's the best practice here? Pros and cons?

推荐答案

在大多数情况下,无论哪种方式都无关紧要。由于 -autorelease 只是意味着对象将在运行循环的当前迭代结束时释放,对象将以任一方式释放。

In most cases, it wont really matter either way. Since -autorelease simply means that the object will be released at the end of the current iteration of the run loop, the object will get released either way.

使用 -autorelease 的最大好处是你不必担心方法上下文中对象的生命周期。因此,如果您稍后决定在上次使用后要对对象执行多行操作,则无需担心将调用移至 -release

The biggest benefit of using -autorelease is that you don't have to worry about the lifetime of the object in the context of your method. So, if you decide later that you want to do something with an object several lines after it was last used, you don't need to worry about moving your call to -release.

使用 -release 时的主要实例与使用相比会有显着差异-autorelease 是您在方法中创建很多的临时对象。例如,请考虑以下方法:

The main instance when using -release will make a noticeable difference vs. using -autorelease is if you're creating a lot of temporary objects in your method. For example, consider the following method:

- (void)someMethod {
    NSUInteger i = 0;
    while (i < 100000) {
        id tempObject = [[[SomeClass alloc] init] autorelease];

        // Do something with tempObject

       i++;
    }
}

到这个方法结束时,你已经有了坐在自动释放池中的100,000个对象等待释放。根据 tempObject 的类,这可能是也可能不是桌面上的主要问题,但它肯定会出现在内存受限的iPhone上。因此,如果要分配许多临时对象,则应该在 -autorelease 上使用 -release 。但是,对于许多/大多数用途,您不会发现两者之间存在任何重大差异。

By the time this method ends, you've got 100,000 objects sitting in the autorelease pool waiting to be released. Depending on the class of tempObject, this may or may not be a major problem on the desktop, but it most certainly would be on the memory-constrained iPhone. Thus, you should really use -release over -autorelease if you're allocating many temporary objects. But, for many/most uses, you wont see any major differences between the two.

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

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