3

What is the difference between initializing array with

NSArray * array = [NSArray array];

and

NSArray * array = @[];

2 Answers 2

9

@[] is shorthand for:

id a = nil;
NSArray* array = [NSArray arrayWithObjects:&a count:0];

Which is really just shorthand for [NSArray array], for all intents and purposes.

This is a feature added in a particular version of the compiler (and doesn't actually require runtime support for this particular syntax).

It is not at all like the @"" shorthand in that @"" produces a compile time constant and will cause no messaging at runtime. In fact, @"" (any @"sequence") is a special case in that it emits a compile time constant that is realized in the runtime with zero messaging; zero dynamism. A @"..." is more similar to an Objective-C class than it is to a regular instance of an object.

Sign up to request clarification or add additional context in comments.

2 Comments

I think @"" produces an NSString object not a compile time constant.
Nope; it really is a compile time constant that is loaded via the dynamic linker just like classes and other compile time emitted data. There is no messaging involved.
7

NSArray * array = @[]; is the new way of doing NSArray * array = [NSArray array];

3 Comments

1. Unrelated to the version of Xcode (rather related to the version of the language/standard/compiler used, of which Xcode is neither one). 2. "It's the same as NSString *string = @"";" - I don't think so. The former creates an array, the latter creates a string.
A good guess, but mostly incorrect. First statement is correct, rest is wrong.
yes, that is correct. Wrote my answer to quickly. Edited my answer. My bad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.