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

前端 未结 2 1048
时光取名叫无心
时光取名叫无心 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:48

    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.

提交回复
热议问题