我有一个存储在plist中的字典数组。字典键是:globalKey和moneyKey。
现在我想在数组中搜索特定的键值。如果键值存在,我需要使用另一个键的新值更新字典。
示例:我需要搜索密钥@“globalKey”的值为5.如果值5存在,我需要使用密钥@“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];
答案 0 :(得分: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];
希望这可以帮助你。
答案 1 :(得分:0)
您可以使用NSPredicate搜索字典数组,如下所示:
NSPredicate * predicate = [NSPredicate predicateWithFormat:@“globalKey == 5”]; NSArray * predicateArray = [array filteredArrayUsingPredicate:predicate];