Reputation: 161
I have an array of dictionaries stored in plist. Dictionary keys are: globalKey and moneyKey.
Now I'd like to search the array for a specific key value. If the key value exists, I need to update the dictionary with the new value for the other key.
Example: I need to search the key @"globalKey" for value 5. If the value 5 exists I need to update that dictionary with the new value for the key @"moneyKey" and save it to the plist.
What would be the best approach for this?
This is how I add new dictionary:
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];
Upvotes: 0
Views: 2266
Reputation:
If I understand what you're trying to do correctly then I think you could try something like this:
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];
Hope this helps you out.
Upvotes: 1
Reputation: 3408
You can use NSPredicate to search Array of Dictionary as follows:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"globalKey == 5"]; NSArray *predicateArray = [array filteredArrayUsingPredicate:predicate];
Upvotes: 0