Skip to content

Instantly share code, notes, and snippets.

@nicktoumpelis
Created August 27, 2014 09:51
Show Gist options
  • Save nicktoumpelis/a4c662656bdb86302409 to your computer and use it in GitHub Desktop.
Save nicktoumpelis/a4c662656bdb86302409 to your computer and use it in GitHub Desktop.
Initialize Core Data stack
- (void)initializeCoreDataStack
{
// Some error checking is necessary...
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"ProjectName" withExtension:@"momd"];
NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
NSPersistentStoreCoordinator *persistentStoreCoordinator =
[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
NSManagedObjectContext *managedObjectContext =
[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator];
self.managedObjectContext = managedObjectContext;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSFileManager *defaultFileManager = [NSFileManager defaultManager];
NSURL *applicationDocumentDirectoryURL =
[[defaultFileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *storeURL = [applicationDocumentDirectoryURL URLByAppendingPathComponent:@"ProjectName.sqlite"];
NSError *error = nil;
NSPersistentStore *store = [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:&error];
if (!store) {
// ...
}
dispatch_sync(dispatch_get_main_queue(), ^{
// update the UI
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment