-1

我有一个问题(我认为)可能与范围有关,但我不确定。我正在尝试做一些我认为应该很简单的事情,但我得到了一个奇怪的结果,我真的可以使用一些建议。我会说我是一个早期目标 c 程序员,但不是一个完整的新手。

我在objective-c 中编写了一个函数,我想用它来更改可变字典对象的可变数组中的键名。所以,我想传入一个可变字典对象的可变数组,并返回具有相同字典对象的相同可变数组,但更改了一些键名。有道理?

我在这段代码中尝试了几个日志语句,这似乎表明我所做的一切都在工作,除了 for 循环完成执行时(当我尝试测试 temp 数组中的值时),数组似乎包含仅源数组中的最后一个元素,重复 [source count] 次。通常,这会让我相信我没有正确写入新值,或者没有正确读取它们,甚至我的 NSLog 语句没有向我展示我认为它们是什么。但这可能是因为范围吗?数组是否不会在 for 循环之外保留其更改?

我已经在这个功能上投入了相当多的时间,而且我已经用尽了我的技巧。任何人都可以帮忙吗?

-(NSMutableArray *)renameKeysIn:(NSMutableArray*)source {
/*
// Pre:
// The source array is an array of dictionary items.
// This method renames some of the keys in the dictionary elements, to make sorting easier later. 
// - "source" is input, method returns a mutable array
 */

// copy of the source array
NSMutableArray *temp = [source mutableCopy];

// a temporary dictionary object:
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];

// These arrays are the old field names and the new names
NSMutableArray *originalField = [NSMutableArray arrayWithObjects:@"text", @"created_at",nil];
NSMutableArray *replacedField = [NSMutableArray arrayWithObjects:@"title", @"pubDate", nil];

// loop through the whole array
for (int x =0; x<[temp count]; x++) {
    // set the temp dictionary to current element
    [dict setDictionary:[temp objectAtIndex:x]]; 

    // loop through the number of keys (fields) we want to replace (created_at, text)... defined in the "originalField" array 
    for (int i=0; i<[originalField count]; i++)
    {   
            // look through the NSDictionary item (fields in the key list)
            // if a key name in the dictionary matches one of the ones to be replaced, then replace it with the new one
            if ([dict objectForKey:[originalField objectAtIndex:i]] != nil) {
                // add a new key/val pair: the new key *name*, and the old key *value* 
                [dict setObject:[dict objectForKey:[originalField objectAtIndex:i]] 
                         forKey:[replacedField objectAtIndex:i]];
                // remove the old key/value pair
                [dict removeObjectForKey:[originalField objectAtIndex:i]];
            }// end if dictionary item not null

    }// end loop through keys (created_at, text)

    [temp replaceObjectAtIndex:x withObject:dict];

}// end loop through array

// check array contents
for (int a=0; a<[temp count]; a++){
    NSLog(@"Temp contents: ############ %@",[[temp objectAtIndex:a] objectForKey:@"pubDate"]);
}

return temp;    
} // end METHOD
4

1 回答 1

0

我认为问题在于:

[dict setDictionary:[temp objectAtIndex:x]];

由于这些东西几乎都在指针中工作(而不是复制内容),所以临时数组的每个元素都将指向 dict 字典,该字典设置为最新键的字典。我认为设置实际指针将解决问题。

dict = [temp objectAtIndex:x];
于 2012-06-20T14:23:06.710 回答