-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCoreDataStack.m
96 lines (74 loc) · 2.26 KB
/
CoreDataStack.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//
// CoreDataStack.m
// RCTCoreData
//
// Created by Seven on 6/4/15.
// Copyright (c) 2015 Facebook. All rights reserved.
//
#import "CoreDataStack.h"
@import CoreData;
@interface CoreDataStack ()
@end
@implementation CoreDataStack
#pragma mark - Public APIs
+ (instancetype)sharedInstance {
static CoreDataStack *stack = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
stack = [[CoreDataStack alloc] init];
});
return stack;
}
- (void)setupWithModelFileName:(NSString *)modelFileName {
if (self.modelFileName) return;
self.modelFileName = modelFileName;
[self store];
}
- (void)saveContext {
NSError *error;
if (self.context.hasChanges && ![self.context save:&error]) {
NSLog(@"Could not save: %@, %@", error, error.userInfo);
}
}
#pragma mark - Properties
- (NSManagedObjectContext *)context {
if (!_context) {
_context = [[NSManagedObjectContext alloc] init];
_context.persistentStoreCoordinator = self.coordinator;
}
return _context;
}
- (NSPersistentStoreCoordinator *)coordinator {
if (!_coordinator) {
_coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.model];
}
return _coordinator;
}
- (NSManagedObjectModel *)model {
if (!_model) {
NSBundle *bundle = [NSBundle mainBundle];
NSURL *modelURL = [bundle URLForResource:self.modelFileName withExtension:@"momd"];
_model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}
return _model;
}
- (NSPersistentStore *)store {
if (!_store) {
NSURL *documentsURL = [self applicationDocumentsDirectory];
NSURL *storeURL = [documentsURL URLByAppendingPathComponent:self.modelFileName];
NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption: @(YES)};
NSError *error;
_store = [self.coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error];
if (!_store) {
NSLog(@"Error adding persistent store: %@", error);
abort();
}
}
return _store;
}
#pragma mark - Helpers
- (NSURL *)applicationDocumentsDirectory {
NSFileManager *manager = [NSFileManager defaultManager];
return [[manager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
}
@end