what is the use of @[ ] in objective c [duplicate]

一曲冷凌霜 提交于 2019-12-22 09:20:13

问题


I have seen

NSArray *objectsToShare = @[objects];

when looking at some example code.

What is the meaning of @[objects] here ?


回答1:


NSArray *objectsToShare = @[objects];

is the same as

NSArray *objectsToShare = [NSArray arrayWithObjects:objects count:count];



回答2:


It is also known as Literals in Objective-C

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




回答3:


It makes a array with one object thats the object "objects"




回答4:


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".



来源:https://stackoverflow.com/questions/15635630/what-is-the-use-of-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!