NSManagedObjectContext extensions

The Core Data framework rules, and its API is really really powerful. But really, why does the Core Data API require us to write so much boilerplate code? Simple things need to be simple.

Why is the deletion of a managed object from the NSManagedObjectContext so easy:

[context deleteObject:someObject];

Compared to its creation:

[NSEntityDescription insertNewObjectForEntityForName:@"someObjectClassName"
                              inManagedObjectContext:context];

Extending NSManagedObjectContext

Add the following category on NSManagedObjectContext to all of your Core Data projects and your pains will be history.

@implementation NSManagedObjectContext (NSManagedObjectContextConvenienceMethods)
 
- (id)newObject:(Class)entity {
    return [NSEntityDescription insertNewObjectForEntityForName:[entity description]
                                         inManagedObjectContext:self];
}
 
@end

Now, a call to create a new object is as easy as deleting it.

[context newObject:[someEntity class]];

Further enhancements of NSManagedObject

Matt Gallagher has written an excellent article about how to further enhance NSManagedObject for adding simple, one-line fetch support. Be sure to check it out.

4 Comments

Vincent DriessenJuly 22nd, 2009 at 09:03

Of course, this only works when you have created a Cocoa class for the entity you want to create.

ElenaLisvatoAugust 6th, 2009 at 17:38

Wow! Thank you! I always wanted to write in my site something like that. Can I take part of your post to my blog?

Vincent DriessenAugust 7th, 2009 at 14:07

@ElenaLisvato: You may, but also include a link to this blogpost then, please.

ExtenzeAugust 17th, 2009 at 18:33

Thank you for your help!

Leave a comment

Your comment