Skip to content

Instantly share code, notes, and snippets.

@hirad
Last active August 29, 2015 14:25
Show Gist options
  • Save hirad/7223ee5c5c738059c9a2 to your computer and use it in GitHub Desktop.
Save hirad/7223ee5c5c738059c9a2 to your computer and use it in GitHub Desktop.
Core Data Basics
// Setting up the stack
NSString* libraryDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
NSString* storePath = [libraryDir stringByAppendingPathComponent:@"store.sqlite"];
NSURL* storeURL = [NSURL fileURLWithPath:storePath];
NSURL* momURL = [[NSBundle mainBundle] URLForResource:@"EmploymentModel" withExtension:@"momd"];
NSManagedObjectModel* mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
NSPersistentStoreCoordinator* psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSDictionary* storeOptions = @{NSMigratePersistentStoresAutomaticallyOption: @YES,
NSInferMappingModelAutomaticallyOption: @YES};
NSError* error = nil;
BOOL success = [psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:storeOptions
error:&error];
if (!success) {
@throw [NSException exceptionWithName:NSInvalidArgumentException
reason:@"Could not initialize Core Data stack with provided parameters." userInfo:@{@"Error": error}];
}
NSManagedObjectContext* context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
context.persistentStoreCoordinator = psc;
// ======================================
// Fetching data
NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"someProperty == %@", someValue];
NSSortDescriptor* sorter = [NSSortDescriptor sortDescriptorWithKey:@"someOtherProperty"
ascending:YES];
fetchRequest.sortDescriptors = @[sorter];
__block NSError* error = nil;
__block NSArray* fetchedObjects;
[self.moc performBlockAndWait:^{
fetchedObjects = [self.moc executeFetchRequest:fetchRequest error:&error];
}];
if (fetchedObjects == nil) {
NSLog(@"Error fetching top performing employees in department \"%@\": %@; %@",
self.department.deptName, [error localizedDescription], [error userInfo]);
return nil;
}
return fetchedObjects;
// ======================================
// Adding new objects
MyManagedObject* object = [NSEntityDescription insertNewObjectForEntityName:@"MyEntity" inManagedObjectContext:someContext];
// ... set the properties on object ...
[someContext performBlock:^{
NSError* saveError = nil;
if (![someContext save:&saveError]) {
NSLog(@"Failed to save: %@; %@", [saveError localizedDescription], [saveError userInfo]);
}
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment