Advertise here

Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Slick's Categories - Core Data

BrianSlickBrianSlick Treadmill Desk NinjaPosts: 10,692Tutorial Authors, Registered Users @ @ @ @ @ @ @ @
edited September 2012 in iOS SDK Development
Just throwing these out there. Feel free to offer suggestions for improvement.
//  NSManagedObject+BTIAdditions.h

#import <CoreData/CoreData.h>

@interface NSManagedObject (BTIAdditions)

+ (NSEntityDescription *)entityDescriptionInContextBTI:(NSManagedObjectContext *)context;
+ (id)managedObjectInContextBTI:(NSManagedObjectContext *)context;

//  NSManagedObject+BTIAdditions.m

#import "NSManagedObject+BTIAdditions.h"

@implementation NSManagedObject (BTIAdditions)

+ (NSEntityDescription *)entityDescriptionInContextBTI:(NSManagedObjectContext *)context
 return [NSEntityDescription entityForName:NSStringFromClass([self class]) inManagedObjectContext:context];

+ (id)managedObjectInContextBTI:(NSManagedObjectContext *)context
   NSEntityDescription *entity = [[self class] entityDescriptionInContextBTI:context];

   return [[[[self class] alloc] initWithEntity:entity insertIntoManagedObjectContext:context] autorelease];


Creating managed objects is a bit cumbersome, even with custom subclasses. There's a lot of this:
NSManagedObjectContext *context = < .... >;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:context];
Car *car = [[Car alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
I normally make properties for the entity descriptions just because they are used over and over again, but I've decided to simplify things with these categories. Now creating an instance is reduced to:
NSManagedObjectContext *context = < .... >;
Car *car = [Car managedObjectInContextBTI:context];
Much cleaner, and you don't have to worry about calling up the entity explicitly. If you do need the entity for some reason, that's easier too:
NSManagedObjectContext *context = < .... >;
NSEntityDescription *entity = [Car entityDescriptionInContextBTI:context];
Professional iOS App Development. Available for hire.
BriTer Ideas LLC - WWW | Facebook | Twitter | LinkedIn

BTIKit | SlickShopper 2 | Leave a PayPal donation
Sign In or Register to comment.