Objective-C 更改 for 循环中的数组内容



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

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

我在此代码中尝试了几个日志语句,这些语句似乎表明我所做的一切都在工作,除了当 for 循环完成执行时(当我尝试测试 temp 数组中的值时),数组似乎只包含源数组中的 LAST 元素,重复 [源计数] 次。通常,这会让我相信我没有正确编写新值,或者没有正确阅读它们,甚至我的 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

我认为问题与:

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

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

dict = [temp objectAtIndex:x];

最新更新