在Objective-C中存储二维数组

时间:2015-03-17 07:31:57

标签: objective-c multidimensional-array

我必须存储属性数组:

   | attr-1 | attr-2 | ...... | attr-n
---------------------------------------
 A | val-A1 | val-A2 | ...... | val-An
---------------------------------------
 B | val-B1 | val-B2 | ...... | val-Bn

现在,我正是这样做的:

NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];

NSDictionary *A =
        [NSDictionary dictionaryWithObjects:
            [NSArray arrayWithObjects:val-A1,
                                      val-A2,
                                      ......,
                                      val-An, nil]
                                    forKeys:
            [NSArray arrayWithObjects:@"attr-1",
                                      @"attr-2",
                                      .........,
                                      @"attr-n", nil]];

NSDictionary *B =
        [NSDictionary dictionaryWithObjects:
            [NSArray arrayWithObjects:val-B1,
                                      val-B2,
                                      ......,
                                      val-Bn, nil]
                                    forKeys:
            [NSArray arrayWithObjects:@"attr-1",
                                      @"attr-2",
                                      .........,
                                      @"attr-n", nil]];

[attributes setObject:A forKey:@"A"];
[attributes setObject:B forKey:@"B"];

这是很多编码。谁知道更好的解决方案?

PS。值不会改变。

1 个答案:

答案 0 :(得分:2)

这样的事可能

NSDictionary *A = @{ @"attr-1" : @1, @"attr-2" : @2 };
NSDictionary *B = @{ @"attr-1" : @4, @"attr-2" : @5 };
NSMutableDictionary *attributes = [@{ @"A" : A, @"B" : B } mutableCopy];

然后,您可以使用此代码

检索5
NSNumber *number = attributes[@"B"][@"attr-2"];
NSLog( @"%d", number.intValue );