Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through NSManagedObjectContext objects?

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?

like image 700
cactus Avatar asked Jan 22 '23 04:01

cactus


2 Answers

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).

like image 103
Tim Avatar answered Feb 01 '23 01:02

Tim


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.

like image 37
Marcus S. Zarra Avatar answered Feb 01 '23 00:02

Marcus S. Zarra