1

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

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

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

4

2 回答 2

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"];
于 2013-02-25T16:20:28.440 回答
0

您还可以使用数组和字典的简写

NSDictionary * dictionary = @{ @"UserId": @123,
  @"UserType": @"blue", 
    @"UserActs": @[@{
           @"ActId": @3,
           @"Time": @1
       }, @{
           @"ActId": @1,
           @"Time": @6
       }]
    };
于 2013-02-25T16:21:24.710 回答