Iterate through NSManagedObjectContext?

I want to iterate over all the objects in my NSManagedObjectContext and update them manually. Then each managed entity must be updated. What is the best way to do this?

+4
source share
3 answers

Theoretically, you can iterate through all entity descriptions in the managed object model, create a query for them without predicates for them, then iterate over all returned objects and perform some updating. 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 that you can bring NSManagedObjects returned as needed by testing for equality of classes (using isKindOfClass: or a method associated with it) or by determining which class is the current entity (using the managedObjectClassName property on an entity in combination with method NSClassWithName() ).

+5
source

This seems like a very difficult approach to the problem. If the data loads with bad data, I would strongly suggest fixing it while you import the data. Tim's answer will work on what you are doing, but I strongly suspect that you are wrong. Iterating over an entire database that searches for potentially bad data is very inefficient.

+4
source

If managed objects are created with "bad data", I would check that you set default values ​​in your model for all properties of all objects. This way you can be sure that whenever you insert an object into your context, it will contain these values. From there, you can configure the properties for everything you need.

0
source

Source: https://habr.com/ru/post/1308261/


All Articles