Skip to content

Instantly share code, notes, and snippets.

@matteom
Last active December 28, 2015 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matteom/7548392 to your computer and use it in GitHub Desktop.
Save matteom/7548392 to your computer and use it in GitHub Desktop.
Core data persistent stack
// Header file
@interface PCPersistentStack : NSObject
@property (readonly) NSManagedObjectContext *managedObjectContext;
- (instancetype)initWithStoreURL:(NSURL*)storeURL modelURL:(NSURL*)modelURL;
- (void)saveContext;
@end
// Implementation file
@import CoreData;
@implementation PCPersistentStack
- (instancetype)initWithStoreURL:(NSURL*)storeURL modelURL:(NSURL*)modelURL {
if (!(self = [super init])) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
self.managedObjectContext.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
NSError* error;
[self.managedObjectContext.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
if (error) {
NSLog(@"error: %@", error);
}
return self;
}
- (void)saveContext {
NSError* error;
[self.managedObjectContext save:&error];
if (error) {
NSLog(@"error: %@", error);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment