2

I were reading another programmer's code, so i found this:

@property(nonatomic, strong) NSArray *assets;
----
   _assets = [@[] mutableCopy];
    __block NSMutableArray *tmpAssets = [@[] mutableCopy];

Is it some kind of trick? Why does he used mutableCopy to immutable array assets ? Why doesn't he just create it like:

self.assets = [NSArray new];
__block NSMutableArray *tmpAssets = [NSMutableArray new];

?

Zaporozhchenko Oleksandr
  • 4,660
  • 3
  • 26
  • 48
  • 2
    Just because the *property* `assets` is immutable that doesn't necessarily mean the *instance variable* that backs it, `_assets`, is immutable. It's good practice to never make any property have mutable type. It's convenient to back a mutable indexed collection property with an `NSMutableArray*` instance variable but only allow it to be mutated through the [indexed collection mutation accessors](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/AccessorConventions.html#//apple_ref/doc/uid/20002174-SW11). – Ken Thomases Jun 17 '15 at 08:57

1 Answers1

1

Just a shorthand to get an empty mutable array.

Instead of [NSMutableArray alloc] init] it's slightly less code to write -

the new construct isn't really used by the majority of Objective-C programmers and was added as a convenience to newcomers from other languages.

Mind that @[] will create an (immutable) NSArray -
there is no Objective-C literal for NSMutableArray.

cacau
  • 3,606
  • 3
  • 21
  • 42