By Vincent Driessen
on Monday, June 22, 2009

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.

If you want to get in touch, I'm @nvie on Twitter.