替换cocoa中字典数组中的所有键

时间:2013-06-18 08:27:01

标签: cocoa nsarray nsdictionary

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

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;
    }

})

2 个答案:

答案 0 :(得分:0)

你几乎就在那里,唯一的问题是对allObjects的调用,你发现它以某种任意顺序返回对象。而是定义原始键的数组:

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

其中的元素与myDictFnalKeys中的替换元素的顺序相同。现在将allObjects的调用替换为:

[myDict objectsForKeys:originalKeys notFoundMarker:NSNull.null]

这将返回与originalKeys中的按键匹配的对象数组(如果缺少某个键,则结果数组将包含notFoundMarker所有的内容 - {在这种情况下{1}}。

这样做,你的代码就可以了。

答案 1 :(得分:0)

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