Objective-C at sign and curly braces, @{ … } what does it mean?

本小妞迷上赌 提交于 2019-12-11 01:23:30

问题


I have this line in Objective-C.

NSMutableArray *mutableArray;
[mutableArray addObject:@{ @"Something" : aObject, @"Otherthing" : anotherObject }];

What does the @{ ... } part do exactly? It is an object, but it seems to create some kind of key, value pair on the fly.


回答1:


It is creating NSDictionary object as you said. Syntax is simple

NSDictionary* dictionary = @{key: object, key: object};

In your example, keys are objects of NSString class. It is important to remember that dictionary copies keys and retains values.




回答2:


These are called Literals. Apple LLVM Compiler 4.0 and above can use this.

In your question, the expression creates a dictionary

NSDictionary *settings = @{ AVEncoderAudioQualityKey : @(AVAudioQualityMax) };

Similarly arrays which were created using NSArray arrayWithArray and other similar methods, can now be done easily

NSArray *array = @[ @"Hello", @"World"]; 

and you will not even need the nil sentinel.

More details here: http://clang.llvm.org/docs/ObjectiveCLiterals.html




回答3:


The @{ ... } syntax is a shorthand way of creating a NSDictionary introduced as part of Modern Objective-C. The syntax @{@"key1": object1, @"key2": object2} is just a shorthand for more verbose methods like [NSDictionary dictionaryWithObjectsAndKeys:] among a few others.



来源:https://stackoverflow.com/questions/22510996/objective-c-at-sign-and-curly-braces-what-does-it-mean

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