Skip to content

Instantly share code, notes, and snippets.

@casspangell
Last active September 17, 2015 00:11
Show Gist options
  • Save casspangell/c357e32c699301a5c197 to your computer and use it in GitHub Desktop.
Save casspangell/c357e32c699301a5c197 to your computer and use it in GitHub Desktop.
Adding, Removing, Updating Elements to CoreData
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
@end
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.303Software.CoreDataExample" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataExample.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this 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();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = 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();
}
}
}
@end
ENTITIES
- Contact
Attributes
name - String
phone - String
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:context];
NSFetchRequest *request = [NSFetchRequest new];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", @"<<name_value>>"];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
// Search for matches and add them to the array
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
NSLog(@"No matches");
}else{
for (int i=0; i<[objects count]; i++) {
matches = objects[i];
//Do something with the matches
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)add:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newContact;
newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contact" inManagedObjectContext:context];
[newContact setValue:@"<<name_value>>" forKey:@"name"];
[newContact setValue:@"<<phone_value>>" forKey:@"phone"];
NSError *error;
[context save:&error];
}
- (IBAction)delete:(id)sender {
// Setup the Fetch Request
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:context];
NSFetchRequest *request = [NSFetchRequest new];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", @"<<name_value>>"];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
// Search for matches and add them to the array
NSArray *objects = [context executeFetchRequest:request error:&error];
// Create NSManagedObject
NSManagedObject *deleteContact;
deleteContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contact" inManagedObjectContext:context];
[deleteContact setValue:@"<<name_value>>" forKey:@"name"];
[deleteContact setValue:@"<<phone_value>>" forKey:@"phone"];
if ([objects count] == 0) {
NSLog(@"No matches");
}else{
// Delete all objects that matched. Use obejects[objectAtIndex:0] to grab the first (and only)
for (int i=0; i<[objects count]; i++) {
[context deleteObject:deleteContact];
}
}
//ALSO:
// Search for matches and add them to the array
NSArray *objects = [context executeFetchRequest:request error:&error];
for (NSManagedObject *object in objects) {
[context deleteObject:object];
}
}
- (IBAction)update:(id)sender {
// Setup the Fetch Request
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:context];
NSFetchRequest *request = [NSFetchRequest new];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", @"303Software"];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
// Search for matches and add them to the array
NSArray *objects = [context executeFetchRequest:request error:&error];
// Create NSManagedObject
NSManagedObject *updateContact;
updateContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contact" inManagedObjectContext:context];
[updateContact setValue:@"<<name_value>>" forKey:@"name"];
[updateContact setValue:@"<<phone_value>>" forKey:@"phone"];
if ([objects count] == 0) {
NSLog(@"No matches");
}else{
for (int i=0; i<[objects count]; i++) {
matches = objects[i];
[updateContact setValue:@"<<name_value>>" forKey:@"name"];
[updateContact setValue:@"<<phone_value>>" forKey:@"phone"];
NSError *error;
[context save:&error];
}
}
//OR (WORKS) start example
// Setup the Fetch Request
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Hazard" inManagedObjectContext:context];
NSFetchRequest *request = [NSFetchRequest new];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(date = %@)", hazard.date];
[request setPredicate:pred];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
NSManagedObject* updateHazard = [objects objectAtIndex:0];
[updateHazard setValue:hazard.reporter forKey:@"reporter"];
[updateHazard setValue:hazard.date forKey:@"date"];
[updateHazard setValue:hazard.type forKey:@"type"];
[updateHazard setValue:hazard.details forKey:@"details"];
[updateHazard setValue:hazard.priority forKey:@"priority"];
[updateHazard setValue:hazard.address forKey:@"address"];
[updateHazard setValue:hazard.mapImageData forKey:@"mapImage"];
[updateHazard setValue:hazard.media1 forKey:@"media1"];
[updateHazard setValue:hazard.media2 forKey:@"media2"];
[updateHazard setValue:hazard.media1 forKey:@"media3"];
[context save:&error];
//end example
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment