Last active
December 28, 2015 19:09
-
-
Save matteom/7548392 to your computer and use it in GitHub Desktop.
Core data persistent stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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