Skip to content

Instantly share code, notes, and snippets.

@nst
Created April 24, 2010 20:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nst/377930 to your computer and use it in GitHub Desktop.
Save nst/377930 to your computer and use it in GitHub Desktop.
Objective-C category to ease NSManagedObject usage with a single context (.m)
#import "NSManagedObject+NST.h"
@implementation NSManagedObject (NST)
+ (id)create {
NSEntityDescription *entityDecription = [self entity];
NSString *name = [entityDecription name];
return [NSEntityDescription insertNewObjectForEntityForName:name inManagedObjectContext:[self moc]] ;
}
+ (NSManagedObjectContext *)moc {
return [(id)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
- (NSManagedObjectContext *)moc {
return [[self class] moc];
}
+ (NSManagedObjectModel *)mom {
return [(id)[[UIApplication sharedApplication] delegate] managedObjectModel];
}
+ (NSEntityDescription *)entity {
return [[[self mom] entitiesByName] objectForKey:NSStringFromClass([self class])];
}
+ (NSFetchRequest *)allFetchRequest {
NSFetchRequest *fr = [[NSFetchRequest alloc] init];
[fr setEntity:[self entity]];
return [fr autorelease];
}
+ (NSArray *)allObjects {
return [[self moc] executeFetchRequest:[self allFetchRequest] error:nil];
}
+ (NSUInteger)allObjectsCount {
return [[self moc] countForFetchRequest:[self allFetchRequest] error:nil];
}
- (BOOL)save {
return [[self moc] save:nil];
}
- (void)deleteObject {
[[self moc] deleteObject:self];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment