Possible Duplicate:
Should I prefer to use literal syntax or constructors for creating dictionaries and arrays?
Is there any difference between:
NSArray *array = @[@"foo", @"bar"];
and
NSArray *array = [NSArray arrayWithObjects:@"foo", @"bar", nil];
Is one of those more stable, faster, or anything else?
This documentation doesn't mention anything about efficiency directly, but does mention that
is equivalent to
I would have to assume that at an assembly level, the two are identical.
Thus the only difference is preference. I prefer the former, it's faster to type and more direct to understand.
The first is just a syntactic sugar for the second. It’s slightly better because it’s shorter and doesn’t require the sentinel
nil
to mark the end of the list. (When you use the second variant and forget thenil
, you can get some nicely unpredictable behaviour.)If they both do not produce the same assembly, the performance difference is going to be so small it’s not of concern for anybody. This is how the assembly looks for the first case with literal shorthand:
And this is the case with
arrayWithObjects
:I don’t know enough assembly to make conclusions, but they certainly look comparable.
This is a feature new invented in Objective C 3.0
The compiler basically replaces the shortcut with a
[NSArray arrayWithObjects:...]
statement.The same happens with Strings
@"String"
EDIT: Ok, let's say something similar happens :) There actually is no other constructor for a basic string.