[NSMutableArray array] 与 [[NSMutableArray alloc] init] 的区别 [英] Difference between [NSMutableArray array] vs [[NSMutableArray alloc] init]

查看:39
本文介绍了[NSMutableArray array] 与 [[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.

谢谢

推荐答案

因为一开始我用 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 memory leak problems. Now using the first declaration i don't need to release anything

当您出售"一个对象时,这是完全正确的.但在其他情况下,当你在 iOS 上创建一个对象时,你可以在获取现成的自动释放对象和调用 alloc 后调用 release 之间做出选择,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.

编辑 - 2011 年 12 月 18 日: 但是随着 iOS 5 和 ARC 的到来,自动释放机制更加高效,并且没有release,所以 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 array] 与 [[NSMutableArray alloc] init] 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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