Altering ManagedObjects In NSArray
- by Garry
I have an entity called 'Job' with two boolean attributes named 'completed' and 'logged'.
I am trying to retrieve all completed jobs that have not been logged at app start-up and change them to logged. I'm able to get all the completed but unlogged jobs with this fetchRequest:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(completed == %@ && logged == %@)", [NSNumber numberWithBool:YES], [NSNumber numberWithBool:NO]];
I'm then assigning this predicate to a fetchRequest and calling the [managedObjectContext executeFetchRequest:fetchRequest] method to get an array of all Job entities that meet this criteria. This seems to work fine and is returning the correct number of jobs.
What I've been trying to do is loop through the NSArray returned, set the logged attribute to YES and then save. This seems to complete and doesn't return any errors but the changes are not persisted when the application quits. Where am I going wrong?
[fetchRequest setPredicate:predicate];
NSError error;
NSArray jobsToLog = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if ([jobsToLog count] > 0) {
for (int i = 0; i < [jobsToLog count] - 1; i++) {
[[jobsToLog objectAtIndex:i] setLogged:[NSNumber numberWithBool:YES]];
// Commit the changes made to disk
error = nil;
if (![managedObjectContext save:&error]) {
// An error occurred
}
}
}
Thanks in anticipation,