Search code examples
objective-ccocoansarraynsdictionaryobjective-c-literals

Difference between literals and class methods for NSMutableArray and NSMutableDictionary


When I started with OSX/iOS I used

    NSMutableArray *        a1 = [NSMutableArray arrayWithCapacity:123] ;
    NSMutableDictionary *   d1 = [NSMutableDictionary dictionaryWithCapacity:123] ;

Then I discovered the 'simpler' version

    NSMutableArray *        a2 = [NSMutableArray array] ;
    NSMutableDictionary *   d2 = [NSMutableDictionary dictionary] ;

I have now moved to:

    NSMutableArray *        a3 = [@[] mutableCopy] ;
    NSMutableDictionary *   d3 = [@{} mutableCopy] ;

Functionally, they all seem identical: once initialized either way, they can be used regardless of how they were created. Where are the differences?

In particular, should I assume that d3/a3 are more similar to d2/a2 than d1/a1 in terms of memory pre-allocation (or lack thereof) ?

Or is this just a matter of style?


Solution

  • Form one is class factory method that is an optimization useful when you know how large a collection initially needs to be or you know the size will be constant but content may change.

    Form two is a class factory method equivalent to calling new. This may or may not be the same as alloc followed by init, but is effectively the same.

    Form three is implicitly the same as alloc followed by initWithArray: or initWithDictionary: respectively. It's convenient but generates an unneeded immutable instance that is discarded under ARC it may not be clear when it is discarded.

    Use form one or form two generally if you are not going to ever use the immutable instance again elsewhere.