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.

  • http://nvie.com Vincent Driessen

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

  • http://nvie.com Vincent Driessen

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

  • ElenaLisvato

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

  • ElenaLisvato

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

  • http://nvie.com Vincent Driessen

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

  • http://nvie.com Vincent Driessen

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

  • http://www.extenzedeal.com Extenze

    Thank you for your help!

  • http://www.extenzedeal.com Extenze

    Thank you for your help!

blog comments powered by Disqus