自动发布还是之后立即发布更好? [英] Is it better to autorelease or release right after?

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

问题描述

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

例如,

<上一页>UIView *view = [[UIView alloc] initWithFrame...];[自我添加子视图:视图];[查看发布];

我听说有人建议我们使用自动释放而不是立即释放.

所以上面变成了:

<上一页>UIView *view = [[[UIView alloc] initWithFrame...] autorelease];[自我添加子视图:视图];

这里的最佳做法是什么?利弊?

解决方案

在大多数情况下,这两种方式都无关紧要.由于 -autorelease 只是意味着对象将在当前运行循环的迭代结束时被释放,因此对象将被释放.

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

使用 -release 与使用 -autorelease 相比,主要实例是如果您创建 a lot方法中的临时对象.例如,考虑以下方法:

- (void)someMethod {NSUInteger i = 0;而(i <100000){id tempObject = [[[SomeClass alloc] init] autorelease];//用 tempObject 做一些事情我++;}}

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

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 example,

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.

So the above becomes:

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

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

解决方案

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.

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.

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++;
    }
}

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天全站免登陆