0

我有一个由字典数组组成的可变数组:

NSArray *myArray    
({
    {
        "COL_1" = Jhon;
        "COL_2" = 01/27/13;
        "COL_3" = THAILAND;
        "COL_4" = 5000;
        "COL_5" = No;
    },
    {
        "COL_1" = Peter;
        "COL_2" = 01/27/13;
        "COL_3" = US;
        "COL_4" = 4000;
        "COL_5" = No;
    }
 })

数组中的所有字典都具有相同的键。我想用一组来自 NSArray 的新密钥替换现有密钥。最终的数组应该像 -

NSArray *myArray    
({
    {
        "A" = Jhon;
        "B" = 01/27/13;
        "C" = THAILAND;
        "D" = 5000;
        "E" = No;
    },
    {
        "A" = Peter;
        "B" = 01/27/13;
        "C" = US;
        "D" = 4000;
        "E" = No;
    }
 })

我不想要一个嵌套的 for 循环,在该循环中我必须遍历数组中的每个元素,并再次遍历每个字典,遍历每个键,以更改键。我所做的如下:

NSArray *myDictFnalKeys = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",nil];  // Here we have set our own keys which will replace the existing keys .
NSMutableArray *myNewArray = [[[NSMutableArray alloc] init] autorelease]; //create a new mutable dictionary
for (id myArrayInstance in array) {
            NSDictionary *myNewDict = [[NSDictionary alloc] initWithObjects:[myArrayInstance allObjects] forKeys:myDictFnalKeys]; // copy the object values from old dictionary and keys from the new array.
            [myNewArray addObject:myNewDict];
    }

问题是字典的值没有按正确的顺序排列。[myArrayInstance allObjects] 没有返回正确的顺序,因此最终数组的顺序不正确。它的到来就像-

NSMutableArray *newArray
({
    {
        A = "01/27/13";
        B = No;
        C = Jhon;
        D = 5000;
        E = THAILAND;
    },
    {
        A = "01/27/13";
        B = No;
        C = Peter;
        D = 4000;
        E = US;
    }

})

4

2 回答 2

0

您可以使用 'objectsForKeys:notFoundMarker:' 按请求的顺序获取值。传递 [NSNULL null] 作为第二个参数。(这真的没关系,所有的值都存在于字典中,并且您没有尝试获取未定义键的值。)

于 2013-06-18T13:10:35.690 回答
0

你快到了,唯一的问题是allObjects你发现的调用以任意顺序返回对象。而是定义原始键的数组:

NSArray *originalKeys = @[@"COL_1", @"COL_2", @"COL_3", @"COL_4", @"COL_5"];

其中元素的顺序与您的myDictFnalKeys. 现在将调用替换为allObjects

[myDict objectsForKeys:originalKeys notFoundMarker:NSNull.null]

这将返回一个与键匹配的对象数组(如果缺少键,则结果数组将包含任何内容-在这种情况下)。originalKeysnotFoundMarkerNSNull.null

这样做,您的代码将起作用。

于 2013-06-18T09:57:19.650 回答