2012-05-31 71 views
0

我有一個存儲在plist中的字典數組。字典鍵是:globalKey和moneyKey。NSDictionary搜索關鍵字和更新值

現在我想搜索一個特定的鍵值的數組。如果鍵值存在,我需要用另一個鍵的新值更新詞典。

示例:我需要在key @「globalKey」中搜索值5。如果值5存在,則需要使用key @「moneyKey」的新值更新該字典並將其保存到plist。

什麼是最好的方法呢?

這是我如何添加新字典:

array = [NSMutableArray arrayWithContentsOfFile:filePath]; 
NSDictionary *newDict = [[NSDictionary alloc] init]; 
newDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:month],@"globalKey", [NSNumber numberWithFloat:money], @"moneyKey", nil]; 
[array addObject:newDict]; 
[array writeToFile:filePath atomically:YES]; 

回答

1

如果我明白你正確地做那麼我想你可以嘗試這樣的事:

NSMutableArray *myArray = [[NSMutableArray alloc] init]; // YOUR STARTING ARRAY OF NSDICTIONARIES 

NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init]; 
NSMutableArray *dictionariesToReplace = [[NSMutableArray alloc] init]; 

for (int i=0; i < [myArray count]; i++) 
{ 
    // Pull out the value to check 
    int valToCheck = [[[myArray objectAtIndex:i] valueForKey:@"globalKey"] intValue]; 

    // Check if a match was made 
    if (valToCheck == 5) 
    { 
     // Make a copy of the existing NSDictionary 
     NSMutableDictionary *newDictionary = [[myArray objectAtIndex:i] mutableCopy]; 
     [newDictionary setValue:@"NEW VALUE" forKey:@"moneyKey"]; 

     // Add the dictionary to the array and update the indexset 
     [dictionariesToReplace addObject:newDictionary]; 
     [indexSet addIndex:i]; 
    } 
} 

// Update the array with the new dictionaries 
[myArray replaceObjectsAtIndexes:indexSet withObjects:dictionariesToReplace]; 

希望這有助於你出去。

+0

謝謝先生,您的回答非常好!只有一件小事是錯誤的。它應該是([myArray count])而不是([myArray count] - 1)。其他一切都很棒。 – maxus182

+0

@ maxus182很高興我能幫上忙!我已經更新了循環 - 我的錯誤是愚蠢的。 –

0

您可以使用NSPredicate來搜索詞典的數組如下:

NSPredicate *謂詞= [NSPredicate predicateWithFormat:@ 「globalKey == 5」 ]。 NSArray * predicateArray = [array filteredArrayUsingPredicate:predicate];