Objective-C at sign and curly braces, @{ … } what

2019-07-18 15:22发布

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.

3条回答
Anthone
2楼-- · 2019-07-18 15:44

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.

查看更多
趁早两清
3楼-- · 2019-07-18 15:56

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.

查看更多
一夜七次
4楼-- · 2019-07-18 16:03

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

查看更多
登录 后发表回答