I want to iterate through all of the objects in my NSManagedObjectContext, and update them manually. Then, every managed object should be updated. What's the best way to do this?
Theoretically you could iterate through all the entity descriptions in your managed object model, build a no-predicate fetch request for them, then loop over all the returned objects and do some update. Example:
// Given some NSManagedObjectContext *context
NSManagedObjectModel *model = [[context persistentStoreCoordinator]
managedObjectModel];
for(NSEntityDescription *entity in [model entities]) {
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entity];
NSError *error;
NSArray *results = [context executeFetchRequest:request error:&error];
// Error-checking here...
for(NSManagedObject *object in results) {
// Do your updates here
}
}
Note you can cast the NSManagedObjects returned as necessary either by testing for class equality (using isKindOfClass:
or a related method) or by figuring out what class the current entity is (using the managedObjectClassName
property on entity
in conjunction with the NSClassWithName()
method).
This seems like a very heavy handed approach to the problem. If the data is getting loaded with bad data then i would strongly suggest fixing it while you are importing the data. Tim's answer will work for what you are doing but I strongly suspect you are coming at this wrong. Iterrating through the whole database looking for potentially bad data is very inefficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With