Suppose I want to, for example, start creating key/value pairs using an NSMutableDictionary
. I then seem to have at least three options for creating an empty, mutable dictionary with an unspecified capacity:
NSMutableDictionary *mutDict = [[NSMutableDictionary alloc] init]; // 1
NSMutableDictionary *mutDict = [NSMutableDictionary new]; // 2
NSMutableDictionary *mutDict = [NSMutableDictionary dictionary]; // 3
Now, as I understand it, [NSObject new]
is practically (if not exactly?) the same as [[NSObject alloc] init]
. So we can basically merge those two options as far as I'm concerned. Regarding the [NSDictionary dictionary]
method though, the documentation says:
dictionary
Creates and returns an empty dictionary.
+ (id)dictionary
Return Value
A new empty dictionary.
Discussion
This method is declared primarily for use with mutable subclasses of
NSDictionary
.If you don’t want a temporary object, you can also create an empty dictionary using
alloc...
andinit
.
I have a couple of questions regarding this documentation to begin with:
Firstly, why is it even declared in NSDictionary instead of NSMutableDictionary if that is where it is intended to be used?
Secondly, what do they mean by "temporary object" in this context?
In summary: Is there a difference between the third alternative above, compared to the first two? Could it have something to do with autoreleasing objects? Does that even matter in an Automatic Reference Counting (ARC) context?
Note that this question applies to other classes as well, for example [NSData data]
and [NSArray array]
.
I am using XCode 4.6.1 and iOS 6.1. Does it matter which one I use these days, using ARC? Perhaps from some perspective on performance?
Thank you for any clear information on this!