我想用对象和键创建一个NSDictionary,如下面的例子
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
但我需要添加多个寄存器,例如:
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" }
]
}
答案 0 :(得分:6)
如果在编译时值为klnown,则可以使用文字创建结构:
NSDictionary *d = @{
@"people": @[
@{ @"code":@"1" , @"name":@"John" },
@{ @"code":@"2" , @"name":@"Smith" },
@{ @"code":@"3" , @"name":@"Jones" }
]
};
NSLog(@"d: %@", d);
NSLog输出:
dictionary: {
people = (
{
code = 1;
name = John;
},
{
code = 2;
name = Smith;
},
{
code = 3;
name = Jones;
}
);
}
答案 1 :(得分:2)
也许你需要创建NSDictionarys的NSArray。
NSArray *keys1 = [NSArray arrayWithObjects:@"code", @"description", nil];
NSArray *objects1 = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], @"Paul", nil];
NSDictionary *register1 = [NSDictionary dictionaryWithObjects:objects1 forKeys:keys1]
NSArray *keys2 = [NSArray arrayWithObjects:@"code", @"description", nil];
NSArray *objects2 = [NSArray arrayWithObjects:[NSNumber numberWithInt:2], @"Tom", nil];
NSDictionary *register2 = [NSDictionary dictionaryWithObjects:objects2 forKeys:keys2];
NSArray *keys3 = [NSArray arrayWithObjects:@"code", @"description", nil];
NSArray *objects3 = [NSArray arrayWithObjects:[NSNumber numberWithInt:3], @"Robin", nil];
NSDictionary *register3 = [NSDictionary dictionaryWithObjects:objects3 forKeys:keys3];
NSArray *registers = @[register1, register2, register3];
NSLog(@"%@", registers);