I have seen
NSArray *objectsToShare = @[objects];
when looking at some example code.
What is the meaning of @[objects]
here ?
I have seen
NSArray *objectsToShare = @[objects];
when looking at some example code.
What is the meaning of @[objects]
here ?
NSArray *objectsToShare = @[objects];
is the same as
NSArray *objectsToShare = [NSArray arrayWithObjects:objects count:count];
Examples
Immutable array expression:
NSArray *array = @[ @"Hello", NSApp, [NSNumber numberWithInt:42] ];
When using Apple LLVM
compiler 4.0 or later
, arrays, dictionaries, and numbers (NSArray, NSDictionary, NSNumber classes)
can also be created using literal syntax instead of methods.[22] Literal syntax uses the @ symbol combined with [], {}, (),
.
Example without literals:
NSArray *myArray = [NSArray arrayWithObject:someObject];
NSDictionary *myDictionary = [NSDictionary dictionaryWithObject:someObject forKey:@"key"];
NSNumber *myNumber = [NSNumber numberWithInt:myInt];
Example with literals:
NSArray *myArray = @[ someObject ];
NSDictionary *myDictionary = @{ @"key" : someObject };
NSNumber *myNumber = @(myInt);
objc-at-expression : '@' (string-literal | encode-literal | selector-literal | protocol-literal | object-literal)
;
object-literal : ('+' | '-')? numeric-constant
| character-constant
| boolean-constant
| array-literal
| dictionary-literal
;
boolean-constant : '__objc_yes' | '__objc_no' | 'true' | 'false' /* boolean keywords. */
;
array-literal : '[' assignment-expression-list ']'
;
assignment-expression-list : assignment-expression (',' assignment-expression-list)?
| /* empty */
;
dictionary-literal : '{' key-value-list '}'
;
key-value-list : key-value-pair (',' key-value-list)?
| /* empty */
;
key-value-pair : assignment-expression ':' assignment-expression
;
For more info Read this Tutorial
It is a new feature added to the LLVM compiler. You can create an array with
NSArray *array = @[object1, ...];
Note that you cannot create a mutable array and that you do not need to end the list of objects with nil
. Watch the WWDC 2012 video "What's New in LLVM".