格式化字典值

时间:2013-02-25 16:14:56

标签: objective-c dictionary

我需要以下列格式将值存储在字典中:

{ "UserId": 123,
  "UserType": "blue", 
    "UserActs": [{
           "ActId": 3,
           "Time": 1
       }, {
           "ActId": 1,
           "Time": 6
       }]
    }

我知道我需要一个用于初始值的字典和一个用于UserActs的嵌套字典,但我不确定如何为相同的键“ActId”和“Time”存储单独的值。我将如何按照这种格式在字典中添加它们?

2 个答案:

答案 0 :(得分:0)

这是创建该字典的旧的,冗长的方式(有一种新的语法,使用Objective-C文字,但它们不可变,所以我选择了这种方法):

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSNumber numberWithInt:123] forKey:@"UserId"];
[dict setObject:@"blue" forKey:@"UserType"];

NSMutableArray *acts = [[NSMutableArray alloc] init];
[acts addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithInt:3], @"ActId",
    [NSNumber numberWithInt:1], @"Time",
    nil]];
[acts addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithInt:1], @"ActId",
    [NSNumber numberWithInt:6], @"Time",
    nil]];
[dict setObject:acts forKey:@"UserActs"];

答案 1 :(得分:0)

您也可以使用数组和词典的简写

NSDictionary * dictionary = @{ @"UserId": @123,
  @"UserType": @"blue", 
    @"UserActs": @[@{
           @"ActId": @3,
           @"Time": @1
       }, @{
           @"ActId": @1,
           @"Time": @6
       }]
    };