2012-05-31 74 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];