-
Notifications
You must be signed in to change notification settings - Fork 2
/
DataManager.m
231 lines (179 loc) · 7.08 KB
/
DataManager.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
//
// TSCoreDataHelper.m
// The System
//
// Created by Jonathan Bennett on 2012-03-17.
// Copyright (c) 2012 CCI Studios. All rights reserved.
//
#import "DataManager.h"
NSString *const DataManagerDidSaveNotification = @"DataManagerDidSaveNotification";
NSString *const DataManagerDidSaveFailedNotification = @"DataManagerDidSaveFailedNotification";
@interface DataManager (Private)
- (NSString *)sharedDocumentsPath;
@end
@implementation DataManager
@synthesize objectModel = _objectModel;
@synthesize mainObjectContext = _mainObjectContext;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
NSString *const kDataManagerBundleName = nil;
NSString *const kDataManagerModelName = @"Achievements";
NSString *const kDataManagerSQLiteName = @"Achievements";
+ (DataManager *)sharedInstance
{
static dispatch_once_t pred;
static DataManager *sharedInstance = nil;
dispatch_once(&pred, ^{ sharedInstance = [[self alloc] init]; });
return sharedInstance;
}
- (NSManagedObjectModel *)objectModel
{
if (_objectModel)
return _objectModel;
NSBundle *bundle = [NSBundle mainBundle];
if (kDataManagerBundleName) {
NSString *bundleName = [[NSBundle mainBundle] pathForResource:kDataManagerBundleName ofType:@"bundle"];
bundle = [NSBundle bundleWithPath:bundleName];
}
NSString *modelPath = [bundle pathForResource:kDataManagerModelName ofType:@"momd"];
_objectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:modelPath]];
return _objectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator)
return _persistentStoreCoordinator;
NSString *storePath = [[self sharedDocumentsPath] stringByAppendingFormat:kDataManagerSQLiteName];
NSURL *storeURL = [NSURL fileURLWithPath:storePath];
NSDictionary *option = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.objectModel];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:option
error:&error]) {
NSLog(@"Fatal error while creating persistent store: %@", error);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)mainObjectContext
{
if (_mainObjectContext)
return _mainObjectContext;
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(mainObjectContext)
withObject:nil
waitUntilDone:YES];
return _mainObjectContext;
}
_mainObjectContext = [[NSManagedObjectContext alloc] init];
[_mainObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
return _mainObjectContext;
}
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *ctx = [[NSManagedObjectContext alloc] init];
[ctx setPersistentStoreCoordinator:self.persistentStoreCoordinator];
return ctx;
}
- (BOOL)save
{
if (![self.mainObjectContext hasChanges])
return YES;
NSError *error = nil;
if (![self.mainObjectContext save:&error]) {
NSLog(@"Error while saving: %@\n%@", [error localizedDescription], [error userInfo]);
[[NSNotificationCenter defaultCenter] postNotificationName:DataManagerDidSaveFailedNotification
object:error];
return NO;
}
[[NSNotificationCenter defaultCenter] postNotificationName:DataManagerDidSaveNotification object:nil];
return YES;
}
- (NSMutableArray *)searchForEntity:(NSString *)entityName withPredicate:(NSPredicate *)predicate andSortKey:(NSString *)sortKey andSortAscending:(BOOL)sortAscending
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.mainObjectContext];
[request setEntity:entity];
if (request != nil) {
[request setPredicate:predicate];
}
if (sortKey != nil) {
NSSortDescriptor *sortdescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
[request setSortDescriptors:[NSArray arrayWithObject:sortdescriptor]];
}
NSError *error = nil;
NSLog(@"fetching");
NSMutableArray *mutableFetchResults = [[self.mainObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil)
NSLog(@"Couldn't get object for entity %@", entityName);
return mutableFetchResults;
}
- (NSMutableArray *)getObjectsForEntity:(NSString *)entityName withSortKey:(NSString *)sortKey andSortAscending:(BOOL)sortAscending
{
return [self searchForEntity:entityName withPredicate:nil andSortKey:sortKey andSortAscending:sortAscending];
}
- (NSUInteger)countForEntity:(NSString *)entityName withPredicate:(NSPredicate *)predicate
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.mainObjectContext];
[request setEntity:entity];
[request setIncludesSubentities:NO];
if (predicate != nil) {
[request setPredicate:predicate];
}
NSError *error = nil;
NSUInteger count = [self.mainObjectContext countForFetchRequest:request error:&error];
if (count == NSNotFound)
NSLog(@"Couldn't get count for entity %@", entity);
return count;
}
- (NSUInteger)countForEntity:(NSString *)entityName
{
return [self countForEntity:entityName withPredicate:nil];
}
- (BOOL)deleteAllObjectsForEntity:(NSString *)entityName
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.mainObjectContext];
[request setEntity:entity];
[request setIncludesPropertyValues:NO];
NSError *error = nil;
NSArray *fetchResults = [self.mainObjectContext executeFetchRequest:request error:&error];
if (fetchResults != nil) {
for (NSManagedObject *manObj in fetchResults) {
[self.mainObjectContext deleteObject:manObj];
}
} else {
NSLog(@"Couldn't delete objects for entity %@", entityName);
}
return YES;
}
- (NSString *)sharedDocumentsPath
{
static NSString *SharedDocumentsPath = nil;
if (SharedDocumentsPath)
return SharedDocumentsPath;
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
SharedDocumentsPath = [libraryPath stringByAppendingPathComponent:@"Database"];
NSFileManager *manager = [NSFileManager defaultManager];
BOOL isDirectory;
if (![manager fileExistsAtPath:SharedDocumentsPath isDirectory:&isDirectory] || !isDirectory) {
NSError *error;
NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey];
[manager createDirectoryAtPath:SharedDocumentsPath
withIntermediateDirectories:YES
attributes:attr
error:&error];
if (error) {
NSLog(@"Error creating directory path: %@", [error localizedDescription]);
}
}
return SharedDocumentsPath;
}
@end