NSManagedObject: better than sliced bread? (Yes.)
(Update: as usual, Scott Stevenson totally kicked my ass:
+ (EPFoobarMO *)foobarWithDefaultContext
return [NSEntityDescription insertNewObjectForEntityForName:@"Foobar" inManagedObjectContext: [[NSApp delegate] managedObjectContext];
I often forget that I’m a cretin preaching to a crowd of really smart people.)
I kid you not: NSManagedObject and Core Data are becoming some of my favorite coding structures/paradigms ever. (I suppose I have Wolf Rentzsch to thank; by the way, mogenerator v1.1 is out. Check it out.) It’s just so awesome – so nice not to have to futz around with NSUndoManager, NSCoding, and all the other minutiae that some brave souls worked with in years past.
I got rejected – not just deferred, rejected – from the University of Chicago.😦 As such, I don’t really have time to write a very lengthy entry; therefore, I’ll just leave you with this little question/guide.
The official way of instantiating an instance/subclass of NSManagedObject is (I think) to use the NSManagedObject class method
initWithEntity:insertIntoManagedObjectContext:, like so: (we are assuming that there’s an NSManagedObjectModel and NSManagedObjectContext named
NSEntityDescription *e = [[model entitiesByName] objectForKey: @"Foobar"];
EPFoobarMO *foo = [[EPFoobarMO alloc] initWithEntity: e insertIntoManagedObjectContext: context];
Since they’re nice people, Apple gave us a convenience method:
EPFoobarMO *foo = [NSEntityDescription insertNewObjectForEntityForName: @"Foobar" inManagedObjectContext: context];
But if we’re sticking to the MVC paradigm (which we are, aren’t we?), one wants to put the initialization code for the EPFoobarMO object inside the EPFoobarMO .m/.h file.
+ (EPFoobarMO *)foobarWithContext:(NSManagedObjectContext *)context
// According to the docs the object returned is autoreleased
return [NSEntityDescription insertNewObjectForEntityForName:@"Foobar"
But it’s ugly to have to pass the NSManagedObjectContext to the initializer every time. We could stick it inside the app’s controller:
- (EPFoobarMO *) foobar
But that’s a flagrant violation of the MVC rules. (Of course, if you’re ignoring them, then this is an ideal solution. But down that way lies Nyarlathotep.)
Or we could resort to the insanity that is the C preprocessor. (I would give a code sample, but I don’t want to hate myself.)
Anyway, what do you think? Leave comments with your opinions or to alert me of any blatant inaccuracies.