我有一個問題(我認爲)可能與範圍有關,但我不確定。我試圖做一些我認爲應該很簡單的事情,但是我得到了一個奇怪的結果,並且我可以真正使用一些建議。我會說我是一個早期的Objective-C程序員,但不是一個完整的newb。objective-c更改數組內容for循環
我在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
是的 - 就是這樣,非常感謝。我不得不做一個小改動 - 我不得不添加「mutableCopy」,因爲一旦我嘗試修改字典,它就會崩潰。再次感謝! – pereirap