NSArray.array / .new / @ [] / alloc-init之间的区别 [英] Difference between NSArray.array/.new /@[]/alloc-init

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

问题描述

似乎有不同的实例化NSArrays的方法(NSDictionary和其他一些方法相同)。

There seem to be different methods of instantiating NSArrays (same for NSDictionary and some others).

我知道:


  1. [NSArray数组]

  2. [NSArray new]

  3. @ []

  4. [[NSArray alloc] init]

  1. [NSArray array]
  2. [NSArray new]
  3. @[]
  4. [[NSArray alloc] init]

出于可读性原因,我通常坚持使用 [NSArray数组] ,但所有这些之间有什么区别,他们都真的这样做吗?

For readability reasons I usually stick with [NSArray array], but what is the difference between all those, do they all really do the same?

推荐答案

对于所有这些结果都是一样的,你得到一个新的空的不可变数组。但是,不同的方法具有不同的内存管理含义。使用ARC,最终没有区别,但在ARC之前,您必须使用正确的版本或发送适当的保留,释放或自动发布消息。

The result is the same for all of them, you get a new empty immutable array. The different methods have different memory management implications though. Using ARC this makes no difference in the end, but before ARC you would have to use the right version or send appropriate retain, release or autorelease messages.

[NSArray new] [[NSArray alloc] init] 返回一个+1保留计数的数组。在ARC之前,您必须释放或自动释放该数组,否则您将泄漏内存。

[NSArray new] and [[NSArray alloc] init] return an array with an +1 retain count. Before ARC you would have to release or autorelease that array or you'd leak memory.

[NSArray数组] @ [] 返回已经自动释放的数组(保留计数0)。如果你想让它在没有ARC的情况下坚持下去,你必须手动保留它,否则当弹出当前自动释放池时它将被解除分配。

[NSArray array] and @[] return an already autoreleased array (retain count 0). If you want it to stick around without ARC you'd have to manually retain it or it would be deallocated when the current autorelease pool gets popped.

这篇关于NSArray.array / .new / @ [] / alloc-init之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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