-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJxCoreDataStore.m
executable file
·393 lines (289 loc) · 15.9 KB
/
JxCoreDataStore.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
//
// JxCoreDataStore.m
//
// Created by Jeanette Müller on 10/31/13.
//
#import "JxCoreDataStore.h"
#import "Logging.h"
#define kAllowedSync @"allowedSync"
@interface JxCoreDataStore ()
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSString *teamID;
@property (nonatomic,strong,readwrite) NSManagedObjectContext* mainManagedObjectContext;
@property (nonatomic,strong) NSManagedObjectModel* managedObjectModel;
@property (nonatomic,strong) NSPersistentStoreCoordinator* persistentStoreCoordinator;
@end
@implementation JxCoreDataStore
#pragma mark - Public Functions
- (id)initWithStoreName:(NSString *)storeName andTeamID:(NSString *)teamID{
self = [super init];
if (self) {
self.name = storeName;
self.teamID = teamID;
[self setupNotifications];
}
return self;
}
- (void)setiCloudSyncAllowed:(BOOL)allowedSync{
if ([self iCloudSyncAllowed] != allowedSync) {
self.persistentStoreCoordinator = nil;
self.mainManagedObjectContext = nil;
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:allowedSync forKey:kAllowedSync];
[defaults synchronize];
}
- (BOOL)iCloudSyncAllowed{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL allowed = [defaults boolForKey:kAllowedSync];
DLog(@"allowed %d", allowed);
return allowed;
}
- (NSManagedObjectContext*)newPrivateContext{
NSManagedObjectContext* context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
context.persistentStoreCoordinator = self.persistentStoreCoordinator;
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
return context;
}
- (void)saveContext{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.mainManagedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges]){
DLog(@"SAVE------------------");
if (![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"ERROR %@, %@", error, [error userInfo]);
abort();
}
}
}
}
- (void)flushStore{
NSPersistentStoreCoordinator *storeCoordinator = [self persistentStoreCoordinator];
NSPersistentStore *store = [[storeCoordinator persistentStores] lastObject];
NSError *error;
NSURL *storeURL = store.URL;
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
if (storeCoordinator != nil) {
self.mainManagedObjectContext = nil;
}
}
- (void)deleteAllObjects:(NSString *)entityDescription{
LLog();
NSManagedObjectContext *privateContext = [self newPrivateContext];
NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:entityDescription];
NSEntityDescription* entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:privateContext];
[fetchRequest setEntity:entity];
LLog();
NSError *error = nil;
NSArray *resultsAll;
if ((resultsAll = [privateContext executeFetchRequest:fetchRequest error:&error])) {
LLog();
for (NSManagedObject *managedObject in resultsAll) {
[privateContext deleteObject:managedObject];
DLog(@"%@ object deleted",entityDescription);
}
DLog(@"SAVE------------------");
if (![privateContext save:&error]) {
DLog(@"Error deleting %@ - error:%@",entityDescription,error);
}
}
}
- (BOOL)replaceCurrentSQLiteDBWithNewDB:(NSURL *)pathToNewDBFile{
DLog(@"newDB %@", pathToNewDBFile);
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:pathToNewDBFile.path]) {
NSArray *stores = [[self persistentStoreCoordinator] persistentStores];
for(NSPersistentStore *store in stores) {
if ([store.type isEqualToString:NSSQLiteStoreType]) {
[_persistentStoreCoordinator removePersistentStore:store error:nil];
[fileManager removeItemAtPath:store.URL.path error:nil];
}
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[self getDBFileName]];
NSError *error;
if ([fileManager removeItemAtURL:storeURL error:&error]) {
NSLog(@"OLD DB Removed");
}else{
NSLog(@"NO OLD DB FOUND TO REMOVE");
}
if ([self copyExistingDBFileToWorkingdirectory:storeURL]) {
NSLog(@"from %@", pathToNewDBFile);
NSLog(@"to copy %@", storeURL);
if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:[self getSQLiteOptions] error:&error]){
NSLog(@"Oops, could not add PersistentStore");
NSLog(@"ERROR %@, %@", error, [error userInfo]);
}
}else{
NSLog(@"ERROR %@, %@", error, [error userInfo]);
abort();
}
}else{
NSLog(@"neu einzufügende DB existiert nicht");
return NO;
}
return YES;
}
#pragma mark - Private Methods
- (void)setupNotifications{
[[NSNotificationCenter defaultCenter] addObserverForName:NSManagedObjectContextDidSaveNotification
object:nil
queue:nil
usingBlock:^(NSNotification* note) {
if (_mainManagedObjectContext) {
NSManagedObjectContext *moc = self.mainManagedObjectContext;
NSManagedObjectContext *backgroundMoc = note.object;
if (backgroundMoc != nil &&
backgroundMoc != moc &&
moc.persistentStoreCoordinator != nil &&
backgroundMoc.persistentStoreCoordinator == moc.persistentStoreCoordinator &&
moc.persistentStoreCoordinator == [self persistentStoreCoordinator]
) {
// DLog(@"note.object: %@", note.object);
// DLog(@"note.userInfo: %@", note.userInfo);
[moc performBlock:^(){
[moc mergeChangesFromContextDidSaveNotification:note];
[[NSNotificationCenter defaultCenter] postNotificationName:kStoreDidChangeNotification object:note.object userInfo:note.userInfo];
}];
}
}
}];
[[NSNotificationCenter defaultCenter] addObserverForName:NSManagedObjectContextObjectsDidChangeNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
// DLog(@"note.object: %@", note.object);
// DLog(@"note.userInfo: %@", note.userInfo);
// NSArray* insertedObjects = [[note userInfo] objectForKey:NSInsertedObjectsKey] ;
// NSArray* deletedObjects = [[note userInfo] objectForKey:NSDeletedObjectsKey] ;
// NSArray* updatedObjects = [[note userInfo] objectForKey:NSUpdatedObjectsKey] ;
// DLog(@"insertObjects: %@", [insertedObjects description]);
// DLog(@"deletedObjects: %@", [deletedObjects description]);
// DLog(@"updatedObjects: %@", [updatedObjects description]);
}];
}
- (NSManagedObjectContext *)mainManagedObjectContext{
if (_mainManagedObjectContext != nil) {
return _mainManagedObjectContext;
}
if (![NSThread currentThread].isMainThread) {
dispatch_sync(dispatch_get_main_queue(), ^{
(void)[self mainManagedObjectContext];
});
DLog(@"return after init");
return _mainManagedObjectContext;
}
self.mainManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
_mainManagedObjectContext.persistentStoreCoordinator = [self persistentStoreCoordinator];
_mainManagedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
return _mainManagedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:_name withExtension:@"momd"];
self.managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
// NSMappingModel *mappingModel = [[NSMappingModel alloc] initWithContentsOfURL:modelURL];
//
// NSArray *newEntityMappings = [NSArray arrayWithArray:mappingModel.entityMappings];
// for (NSEntityMapping *entityMapping in newEntityMappings) {
//
// [entityMapping setSourceEntityVersionHash:[sourceModel.entityVersionHashesByName valueForKey:entityMapping.sourceEntityName]];
// [entityMapping setDestinationEntityVersionHash:[destinationModel.entityVersionHashesByName valueForKey:entityMapping.destinationEntityName]];
// }
// mappingModel.entityMappings = newEntityMappings;
//
// BOOL ok = [migrationManager migrateStoreFromURL:sourceStoreURL
// type:sourceStoreType
// options:nil
// withMappingModel:mappingModel
// toDestinationURL:destinationStoreURL
// destinationType:destinationStoreType
// destinationOptions:nil
// error:&error];
//
// _managedObjectModel = mappingModel;
return _managedObjectModel;
}
- (NSDictionary *)getSQLiteOptions{
return @{
NSMigratePersistentStoresAutomaticallyOption: @(YES),
NSInferMappingModelAutomaticallyOption: @(YES)
};
}
- (NSString *)getDBFileName{
return [NSString stringWithFormat:@"%@.sqlite", _name];
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{
if (_persistentStoreCoordinator != nil) {
//DLog(@"direct return");
return _persistentStoreCoordinator;
}
if (![NSThread currentThread].isMainThread) {
dispatch_sync(dispatch_get_main_queue(), ^{
(void)[self persistentStoreCoordinator];
});
return _persistentStoreCoordinator;
}
self.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSError *error;
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[self getDBFileName]];
[self copyExistingDBFileToWorkingdirectory:storeURL];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:[self getSQLiteOptions]
error:&error]) {
NSLog(@"ERROR %@, %@", error, [error userInfo]);
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
}
return _persistentStoreCoordinator;
}
- (NSURL *)applicationDocumentsDirectory{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (BOOL)copyExistingDBFileToWorkingdirectory:(NSURL *)storeURL{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
if (![fileManager fileExistsAtPath:storeURL.path]) {
NSString *sqliteFilePath = [[NSBundle mainBundle] pathForResource:_name ofType:@"sqlite"];
NSLog(@"sqliteFilePath %@", sqliteFilePath);
if (sqliteFilePath && [sqliteFilePath isKindOfClass:[NSString class]] && ![sqliteFilePath isEqualToString:@""]) {
if ([fileManager fileExistsAtPath:sqliteFilePath]){
NSURL *documentPath = [NSURL fileURLWithPath:sqliteFilePath];
NSLog(@"documentPath %@", documentPath);
if (![fileManager copyItemAtURL:documentPath toURL:storeURL error:&error]) {
NSLog(@"Oops, could copy preloaded data");
}else{
NSLog(@"kopiere vorhandene sqlite DB an richtigen Ort");
return YES;
}
}else{
NSLog(@"Projekteidene sqlite DB existiert nicht");
}
}else{
NSLog(@"sqliteFilePath nicht definiert");
}
}else{
NSLog(@"DB existiert bereits an richtigem Ort");
return YES;
}
NSLog(@"ERROR %@, %@", error, [error userInfo]);
return NO;
}
- (NSURL *)getURIPrepresentationForID:(NSString *)idString andEntityName:(NSString *)entityName{
NSString *urlString = [self getStringPrepresentationForID:idString andEntityName:entityName];
return [NSURL URLWithString:urlString];
}
- (NSString *)getStringPrepresentationForID:(NSString *)idString andEntityName:(NSString *)entityName{
NSPersistentStoreCoordinator *storeCoordinator = [self persistentStoreCoordinator];
NSDictionary *metaData = [storeCoordinator metadataForPersistentStore:[[storeCoordinator persistentStores] firstObject]];
//DLog(@"SQLITE UUID %@", [metaData objectForKey:NSStoreUUIDKey]);
return [NSString stringWithFormat:@"x-coredata://%@/%@/%@", [metaData objectForKey:NSStoreUUIDKey], entityName, idString];
}
@end