Skip to content

Instantly share code, notes, and snippets.

@JigsChanchiya
Created June 4, 2013 05:50
Show Gist options
  • Save JigsChanchiya/5703865 to your computer and use it in GitHub Desktop.
Save JigsChanchiya/5703865 to your computer and use it in GitHub Desktop.
Coredata helper methods in objective-c
#pragma mark -
#pragma mark - Creating Object
-(id)createObjectForEntity:(NSString *)entityName
{
if (entityName!=nil || [entityName isEqualToString:@""])
{
return [NSEntityDescription
insertNewObjectForEntityForName:entityName
inManagedObjectContext:appDelegate.managedObjectContext];
}
else{
return nil;
}
}
-(id)createObjectForEntity:(NSString *)entityName context:(NSManagedObjectContext *)aContext
{
if (entityName!=nil || [entityName isEqualToString:@""])
{
return [NSEntityDescription
insertNewObjectForEntityForName:entityName
inManagedObjectContext:aContext];
}
else{
return nil;
}
}
#pragma mark -
#pragma mark - Retrive Object
-(NSMutableArray*) getObjectsforEntity:(NSString *)strEntity
{
return [self getObjectsforEntity:strEntity ShortBy:nil isAscending:NO predicate:nil];
}
-(NSMutableArray*) getObjectsforEntity:(NSString *)strEntity ShortBy:(NSString *)strShort isAscending:(BOOL)ascending predicate:(NSPredicate *)predicate
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:strEntity inManagedObjectContext:appDelegate.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setIncludesPendingChanges:NO];
if (strShort)
{
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:strShort ascending:ascending];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[sort release];
}
if (predicate)
{
[fetchRequest setPredicate:predicate];
}
NSError *error;
NSMutableArray *arrAllObjects = (NSMutableArray*)[appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
[arrAllObjects retain];
[fetchRequest release];
return arrAllObjects;
}
#pragma mark -
#pragma mark - Delete Object
-(void)deleteObject:(NSManagedObject *)managedObject
{
NSManagedObjectContext *moc = appDelegate.managedObjectContext;
[moc deleteObject:managedObject];
[appDelegate saveContext];
}
-(void) deleteObjectsForEntity:(NSString *)strEntity
{
NSManagedObjectContext *moc = appDelegate.managedObjectContext;
//---------------Fetching and Deleting Category---------
NSFetchRequest *fetchRequest;
NSEntityDescription *entity;
NSArray *Result;
NSError *error;
//---------------Fetching and Deleting ITems---------
fetchRequest = [[NSFetchRequest alloc] init];
entity = [NSEntityDescription entityForName:strEntity inManagedObjectContext:moc];
[fetchRequest setEntity:entity];
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"library == %@",appDelegate.objLibrary];
// [fetchRequest setPredicate:predicate];
Result = [moc executeFetchRequest:fetchRequest error:nil];
for (NSManagedObject *managedObject in Result)
{
[moc deleteObject:managedObject];
}
error = nil;
[moc save:&error];
}
-(void) deleteObjectsForEntity:(NSString *)strEntity predicate:(NSPredicate *)predicate
{
NSManagedObjectContext *moc = appDelegate.managedObjectContext;
//---------------Fetching and Deleting Category---------
NSFetchRequest *fetchRequest;
NSEntityDescription *entity;
NSArray *Result;
NSError *error;
//---------------Fetching and Deleting ITems---------
fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setPredicate:predicate];
entity = [NSEntityDescription entityForName:strEntity inManagedObjectContext:moc];
[fetchRequest setEntity:entity];
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"library == %@",appDelegate.objLibrary];
// [fetchRequest setPredicate:predicate];
Result = [moc executeFetchRequest:fetchRequest error:nil];
for (NSManagedObject *managedObject in Result)
{
[moc deleteObject:managedObject];
}
error = nil;
[moc save:&error];
}
//In AppDelegate class
#pragma mark -
#pragma mark - Core Data stack
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil)
{
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
- (NSManagedObjectContext *)tempManagedObjectContext
{
if (__tempManagedObjectContext != nil)
{
return __tempManagedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__tempManagedObjectContext = [[NSManagedObjectContext alloc] init];
[__tempManagedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __tempManagedObjectContext;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"COREDATAMODELNAME" withExtension:@"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectoryURL] URLByAppendingPathComponent:@"COREDATAMODELNAME.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment