向nsdictionary添加各种对象和键

Raw*_*Raw 2 objective-c nsdictionary ios

我想用对象和键创建一个NSDictionary,如下例所示

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                   forKeys:keys];
Run Code Online (Sandbox Code Playgroud)

但我需要添加多个寄存器,例如:

code=1
description=John

code=2
description=Paul

code=3
description=Peter
.
.
.

exactly what I need, an NSDictionary like a json structure:
{
"people": [
{ "code":"1" , "name":"John" }, 
{ "code":"2" , "name":"Smith" }, 
{ "code":"3" , "name":"Jones" }
]
}
Run Code Online (Sandbox Code Playgroud)

zap*_*aph 6

如果在编译时值为klnown,则可以使用文字创建结构:

NSDictionary *d = @{
    @"people": @[
        @{ @"code":@"1" , @"name":@"John" },
        @{ @"code":@"2" , @"name":@"Smith" },
        @{ @"code":@"3" , @"name":@"Jones" }
    ]
};
NSLog(@"d: %@", d);
Run Code Online (Sandbox Code Playgroud)

NSLog输出:

dictionary: {
    people =     (
                {
            code = 1;
            name = John;
        },
                {
            code = 2;
            name = Smith;
        },
                {
            code = 3;
            name = Jones;
        }
    );
}
Run Code Online (Sandbox Code Playgroud)