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

前端 未结 2 1046
时光取名叫无心
时光取名叫无心 2020-12-15 11:09

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

I know:

  1. [NSArray array]
2条回答
  •  误落风尘
    2020-12-15 11:56

    Results are same for all of them, you get a new empty immutable array. These methods have different memory management implications though. ARC 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] return an array with retain count is 1. Before ARC you would have to release or autorelease that array or you'd leak memory.

    • [NSArray array], @[] return an already autoreleased array (retain count is 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.

提交回复
热议问题