Basem Saadawy
Basem Saadawy

Reputation: 1818

NSArray initialization methods

What is the difference between initializing array with

NSArray * array = [NSArray array];

and

NSArray * array = @[];

Upvotes: 3

Views: 9700

Answers (2)

bbum
bbum

Reputation: 162722

@[] 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.

Upvotes: 9

Mikael
Mikael

Reputation: 3612

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

Upvotes: 7

Related Questions