Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I express NSDictionary as a literal in Objective-c?

Just like:

"APP_INFO" : {
            "v":"2.0",
            "appid":"1",
            "lang":"zh-Hans",
             }

I cannot use init methods because it's not a compile-time constant.

like image 458
Yifeng Li Avatar asked Jan 17 '23 00:01

Yifeng Li


2 Answers

Starting in Clang 3.2, there's literal container syntax available:

NSDictionary * d = @{
    @"APP_INFO" :  
    @{
        @"v" : @"2.0",
        @"appid" : @"1",
        @"lang" : @"zh-Hans",
}};

This creates an ordinary immutable NSDictionary instance, just as if you had used alloc/initWithObjects:forKeys: or any other method; it's simply nice syntactic sugar.

Rumor has it that Apple will be adding this to their compiler soon, too.

like image 154
jscs Avatar answered Jan 24 '23 02:01

jscs


NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"2.0", @"v", @"1", @"appid", @"1", @"zh-Hans", @"lang", nil];

This creates an immutable dictionary whose contents are fixed at compile time.

You can use the same init method to populate a new dictionary at runtime:

id object1 = ...;
...
NSString *key1 = ...;
...

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:object1, key1, object2, key2, object3, key3, nil];
like image 33
Andrew Madsen Avatar answered Jan 24 '23 01:01

Andrew Madsen