Difference between NSArray.array/.new /@[]/alloc-init

女生的网名这么多〃 提交于 2019-11-27 21:28:40

问题


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

I know:

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

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


回答1:


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] 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 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.




回答2:


  1. [NSArray array] : Create and return an empty array

  2. [NSArray new] : alloc, init and return a NSArray object

  3. @[] : Same as 1.

  4. [[NSArray alloc] init] : Same as 2.

Different between [NSArray array] and [[NSArray alloc] init] is if there are non-ARC:

  • [NSArray array] is an autorelease object. You have to call retain if you want to keep it. E.g when you return an array.

  • [[NSArray alloc] init] is an retained object. So you don't have to call retain more if you want keep it.

With ARC, they are same.



来源:https://stackoverflow.com/questions/33297171/difference-between-nsarray-array-new-alloc-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!