Thursday, July 2, 2009

Core Data - Inserting a New Managed Object

For some reason, it really bugs me that the way that you insert a new managed object into a managed object context is by using a class method on NSEntityDescription. I realize that there is no "one right" abstraction, but every time I've been away from Core Data for a while, it takes me a while to remember how to create and insert a new object because this:

    NSManagedObject *newManagedObject = [NSEntityDescription 
insertNewObjectForEntityForName:[entity name]
inManagedObjectContext:context]
;

is completely non-intuitive for me. Although the entity description is used in the process of inserting a new managed object, there's no way you can claim it's the primary object for that action.

I may be wrong, but I think it was this way in EOF, too. Anyway, the nice thing about having a dynamic language like Objective-C that supports categories is that you don't have to live with things that don't fit your particular way of thinking.

To me, the logical place for a method that inserts a new managed object into a managed object context, would be an instance method on the context, though I could also see an argument for it being a factory method on the managed object as well.

When I'm writing my own Core Data apps, I use this category:

NSManagedObjectContext-insert.h
#import <Cocoa/Cocoa.h>
@interface NSManagedObjectContext(insert)
-(NSManagedObject *) insertNewEntityWithName:(NSString *)name;
@end


NSManagedObjectContext-insert.m
#import "NSManagedObjectContext-insert.h"
@implementation NSManagedObjectContext(insert)
-(NSManagedObject *) insertNewEntityWithName:(NSString *)name
{
return [NSEntityDescription insertNewObjectForEntityForName:name inManagedObjectContext:self];
}

@end


This very short little category allows me to insert new objects into a context by simply doing this:

    [context insertNewEntityWityName:[entity name]];

Which personally, I find a lot easier to remember than the first one.

No comments:

Post a Comment