cactus
cactus

Reputation: 41

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?

Upvotes: 4

Views: 4656

Answers (3)

jinglesthula
jinglesthula

Reputation: 4577

If managed objects are getting created with the 'wrong data', I would check to make sure you've set default values in your model for all properties of all entities. This way you can be sure whenever you insert an object into your context it will contain those values. From there, you can set the properties to whatever you need.

Upvotes: 0

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46718

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.

Upvotes: 4

Tim
Tim

Reputation: 60110

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

Upvotes: 5

Related Questions