[NSMutableArray数组]与[[NSMutableArray alloc] init]之间的区别 [英] Difference between [NSMutableArray array] vs [[NSMutableArray alloc] init]

查看:912
本文介绍了[NSMutableArray数组]与[[NSMutableArray alloc] init]之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我声明一个可变数组的区别:

can someone tell me the difference in declare an mutable array with:

NSMutableArray *array = [NSMutableArray array];

NSMutableArray *array = [[NSMutableArray alloc] init];

因为在开始时我用alloc来声明我的所有数组,如果在某一结束时函数我返回了使用alloc创建的数组,我不得不自动释放该数组,因为内存泄漏问题。

Because in the beginning I was declaring all my arrays with alloc, and if in the end of a certain function I returned the array created with alloc, I had to autorelease that array, because of memory leak problems.

现在使用第一个声明我不需要释放任何东西。

Now using the first declaration I don't need to release anything.

谢谢

推荐答案


因为在开始我用div声明我的所有数组,如果在某个函数的最后我返回使用alloc创建的数组我必须自动释放该数组,因为内存泄漏问题。现在使用第一个声明我不需要释放任何东西

Because in the beginning i was declaring all my arrays with alloc and if in the end of a certain function i returned the array created with alloc i had to autorelease that array, because memory leak problems. Now using the first declaration i don't need to release anything

当你售卖一个物体时,这是完全正确的。但在其他情况下,当您在iOS上创建一个对象时,您可以在获取现成的自动释放对象和调用alloc然后释放之间进行选择,Apple希望您使用alloc和release,因为这样可以保持对象的生命周期简短且受你控制。

That is exactly correct when you "vend" an object. But in other cases, when you create an object on iOS, where you have a choice between obtaining a ready-made autoreleased object and calling alloc followed by release, Apple wants you to use alloc and release, because this keeps the lifetime of the object short and under your control.

这里的问题是自动释放的对象存在于自动释放池中,并且可能会堆积,直到池被耗尽,无论何时都可以。

The problem here is that autoreleased objects live in the autorelease pool and can pile up until the pool is drained, whenever that may be.

需要注意的另一件事是循环。您可能会在不知情的情况下生成自动释放的对象,它们只会堆积在池中。解决方案是在循环开始时创建自己的自动释放池,并在循环结束时释放它,以便每次循环时都释放对象。

Another thing to watch out for is loops. You may generate autoreleased objects without being aware of it, and they just pile up in the pool. The solution is to create your own autorelease pool at the start of the loop and release it at the end of the loop, so that the objects are released each time thru the loop.

编辑 - 12/18/2011:但是对于iOS 5和ARC的出现,自动释放机制效率更高,并且没有发布,因此alloc-init和出售自动释放对象的便利构造函数之间的区别变得毫无意义。 (此外它现在是 @autoreleasepool 块而不是自动释放池(伪)对象。)

EDIT - 12/18/2011: But with iOS 5 and the coming of ARC, the autorelease mechanism is far more efficient, and there is no such thing as release, so the distinction between alloc-init and a convenience constructor vending an autoreleased object becomes moot. (Also it's now an @autoreleasepool block rather than an autorelease pool (pseudo-)object.)

这篇关于[NSMutableArray数组]与[[NSMutableArray alloc] init]之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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