简体   繁体   English

[NSMutableArray数组]与[[NSMutableArray alloc] init]之间的区别

[英]Difference between [NSMutableArray array] vs [[NSMutableArray alloc] init]

can someone tell me the difference in declare an mutable array with: 可以有人告诉我声明一个可变数组的区别:

NSMutableArray *array = [NSMutableArray array];

and

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

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. 因为在开始时我用alloc来声明我的所有数组,如果在某个函数的最后我返回了使用alloc创建的数组,我必须自动释放该数组,因为内存泄漏问题。

Now using the first declaration I don't need to release anything. 现在使用第一个声明我不需要发布任何内容。

Thanks 谢谢

array类方法本身会生成一个自动释放的数组,这意味着您不必(也不应该)手动释放它。

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. 因为在开始时我用alloc声明我的所有数组,如果在某个函数的最后我返回了使用alloc创建的数组,我必须自动释放该数组,因为内存泄漏问题。 Now using the first declaration i don't need to release anything 现在使用第一个声明我不需要发布任何内容

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. 但在其他情况下,当您在iOS上创建一个对象时,您可以在获取现成的自动释放对象和调用alloc然后释放之间做出选择,Apple希望您使用alloc和release,因为这样可以保持对象的生命周期简短而且在你的控制之下。

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. 解决方案是在循环开始时创建自己的自动释放池,并在循环结束时释放它,以便每次通过循环释放对象。

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. 编辑 - 12/18/2011:但是随着iOS 5和ARC的到来,自动释放机制效率更高,并且没有release这样的东西,所以alloc-init和便利构造函数之间的区别是自动释放的对象变得没有实际意义 (Also it's now an @autoreleasepool block rather than an autorelease pool (pseudo-)object.) (它现在是@autoreleasepool块而不是自动释放池(伪)对象。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM