forked from magicalpanda/MagicalRecord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MagicalRecordHelpers.m
492 lines (403 loc) · 17.4 KB
/
MagicalRecordHelpers.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//
// MagicalRecordHelpers.m
//
// Created by Saul Mora on 3/11/10.
// Copyright 2010 Magical Panda Software, LLC All rights reserved.
//
#import "CoreData+MagicalRecord.h"
#import <objc/runtime.h>
static NSString * const kMagicalRecordCategoryPrefix = @"MR_";
#ifdef MR_SHORTHAND
static BOOL methodsHaveBeenSwizzled = NO;
#endif
static id errorHandlerTarget = nil;
static SEL errorHandlerAction = nil;
static BOOL shouldAutoCreateManagedObjectModel_;
static BOOL shouldAutoCreateDefaultPersistentStoreCoordinator_;
//Dynamic shorthand method helpers
BOOL addMagicalRecordShortHandMethodToPrefixedClassMethod(Class class, SEL selector);
BOOL addMagicalRecordShorthandMethodToPrefixedInstanceMethod(Class klass, SEL originalSelector);
void swizzleInstanceMethods(Class originalClass, SEL originalSelector, Class targetClass, SEL newSelector);
void replaceSelectorForTargetWithSourceImpAndSwizzle(Class originalClass, SEL originalSelector, Class newClass, SEL newSelector);
@implementation MagicalRecordHelpers
+ (void) cleanUp
{
errorHandlerTarget = nil;
errorHandlerAction = nil;
[MRCoreDataAction cleanUp];
[NSManagedObjectContext MR_setDefaultContext:nil];
[NSManagedObjectModel MR_setDefaultManagedObjectModel:nil];
[NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:nil];
[NSPersistentStore MR_setDefaultPersistentStore:nil];
}
+ (NSString *) currentStack
{
NSMutableString *status = [NSMutableString stringWithString:@"Current Default Core Data Stack: ---- \n"];
[status appendFormat:@"Context: %@\n", [NSManagedObjectContext MR_defaultContext]];
[status appendFormat:@"Model: %@\n", [[NSManagedObjectModel MR_defaultManagedObjectModel] entityVersionHashesByName]];
[status appendFormat:@"Coordinator: %@\n", [NSPersistentStoreCoordinator MR_defaultStoreCoordinator]];
[status appendFormat:@"Store: %@\n", [NSPersistentStore MR_defaultPersistentStore]];
return status;
}
+ (void) defaultErrorHandler:(NSError *)error
{
NSDictionary *userInfo = [error userInfo];
for (NSArray *detailedError in [userInfo allValues])
{
if ([detailedError isKindOfClass:[NSArray class]])
{
for (NSError *e in detailedError)
{
if ([e respondsToSelector:@selector(userInfo)])
{
MRLog(@"Error Details: %@", [e userInfo]);
}
else
{
MRLog(@"Error Details: %@", e);
}
}
}
else
{
MRLog(@"Error: %@", detailedError);
}
}
MRLog(@"Error Message: %@", [error localizedDescription]);
MRLog(@"Error Domain: %@", [error domain]);
MRLog(@"Recovery Suggestion: %@", [error localizedRecoverySuggestion]);
}
+ (void) handleErrors:(NSError *)error
{
if (error)
{
// If a custom error handler is set, call that
if (errorHandlerTarget != nil && errorHandlerAction != nil)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[errorHandlerTarget performSelector:errorHandlerAction withObject:error];
#pragma clang diagnostic pop
}
else
{
// Otherwise, fall back to the default error handling
[self defaultErrorHandler:error];
}
}
}
+ (id) errorHandlerTarget
{
return errorHandlerTarget;
}
+ (SEL) errorHandlerAction
{
return errorHandlerAction;
}
+ (void) setErrorHandlerTarget:(id)target action:(SEL)action
{
errorHandlerTarget = target; /* Deliberately don't retain to avoid potential retain cycles */
errorHandlerAction = action;
}
- (void) handleErrors:(NSError *)error
{
[[self class] handleErrors:error];
}
+ (void) setDefaultModelNamed:(NSString *)modelName;
{
NSManagedObjectModel *model = [NSManagedObjectModel MR_managedObjectModelNamed:modelName];
[NSManagedObjectModel MR_setDefaultManagedObjectModel:model];
}
+ (void) setDefaultModelForTestCase:(Class)aClass;
{
NSBundle *bundle = [NSBundle bundleForClass:aClass];
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:bundle]];
[NSManagedObjectModel MR_setDefaultManagedObjectModel:model];
}
+ (NSString *) defaultStoreName;
{
NSString *defaultName = [[[NSBundle mainBundle] infoDictionary] valueForKey:(id)kCFBundleNameKey];
if (defaultName == nil)
{
defaultName = kMagicalRecordDefaultStoreFileName;
}
if (![defaultName hasSuffix:@"sqlite"])
{
defaultName = [defaultName stringByAppendingPathExtension:@"sqlite"];
}
return defaultName;
}
+ (void) setupCoreDataStack
{
NSManagedObjectContext *context = [NSManagedObjectContext MR_context];
[NSManagedObjectContext MR_setDefaultContext:context];
}
+ (void) setupAutoMigratingCoreDataStack
{
[self setupCoreDataStackWithAutoMigratingSqliteStoreNamed:[self defaultStoreName]];
}
+ (void) setupCoreDataStackWithStoreNamed:(NSString *)storeName
{
NSPersistentStoreCoordinator *coordinator = [NSPersistentStoreCoordinator MR_coordinatorWithSqliteStoreNamed:storeName];
[NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:coordinator];
NSManagedObjectContext *context = [NSManagedObjectContext MR_contextWithStoreCoordinator:coordinator];
[NSManagedObjectContext MR_setDefaultContext:context];
}
+ (void) setupCoreDataStackWithAutoMigratingSqliteStoreNamed:(NSString *)storeName
{
NSPersistentStoreCoordinator *coordinator = [NSPersistentStoreCoordinator MR_coordinatorWithAutoMigratingSqliteStoreNamed:storeName];
[NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:coordinator];
NSManagedObjectContext *context = [NSManagedObjectContext MR_contextWithStoreCoordinator:coordinator];
[NSManagedObjectContext MR_setDefaultContext:context];
}
+ (void) setupCoreDataStackWithInMemoryStore;
{
NSPersistentStoreCoordinator *coordinator = [NSPersistentStoreCoordinator MR_coordinatorWithInMemoryStore];
[NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:coordinator];
NSManagedObjectContext *context = [NSManagedObjectContext MR_contextWithStoreCoordinator:coordinator];
[NSManagedObjectContext MR_setDefaultContext:context];
}
#pragma mark - iCloud Methods
+ (BOOL) isICloudEnabled;
{
NSURL *cloudURL = [NSPersistentStore MR_cloudURLForUbiqutiousContainer:nil];
return cloudURL != nil;
}
+ (void) setupCoreDataStackWithiCloudContainer:(NSString *)icloudBucket localStoreNamed:(NSString *)localStore;
{
[self setupCoreDataStackWithiCloudContainer:icloudBucket contentNameKey:nil localStoreNamed:localStore cloudStorePathComponent:nil];
}
+ (void) setupCoreDataStackWithiCloudContainer:(NSString *)containerID contentNameKey:(NSString *)contentNameKey localStoreNamed:(NSString *)localStoreName cloudStorePathComponent:(NSString *)pathSubcomponent;
{
[self setupCoreDataStackWithiCloudContainer:containerID contentNameKey:contentNameKey localStoreNamed:localStoreName cloudStorePathComponent:pathSubcomponent completion:nil];
}
+ (void) setupCoreDataStackWithiCloudContainer:(NSString *)containerID contentNameKey:(NSString *)contentNameKey localStoreNamed:(NSString *)localStoreName cloudStorePathComponent:(NSString *)pathSubcomponent completion:(void(^)(void))completion;
{
NSPersistentStoreCoordinator *coordinator = [NSPersistentStoreCoordinator MR_coordinatorWithiCloudContainerID:containerID
contentNameKey:contentNameKey
localStoreNamed:localStoreName
cloudStorePathComponent:pathSubcomponent
completion:completion];
[NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:coordinator];
NSManagedObjectContext *context = [NSManagedObjectContext MR_contextWithStoreCoordinator:coordinator];
[NSManagedObjectContext MR_setDefaultContext:context];
}
#pragma mark - Options
+ (BOOL) shouldAutoCreateManagedObjectModel;
{
return shouldAutoCreateManagedObjectModel_;
}
+ (void) setShouldAutoCreateManagedObjectModel:(BOOL)shouldAutoCreate;
{
shouldAutoCreateManagedObjectModel_ = shouldAutoCreate;
}
+ (BOOL) shouldAutoCreateDefaultPersistentStoreCoordinator;
{
return shouldAutoCreateDefaultPersistentStoreCoordinator_;
}
+ (void) setShouldAutoCreateDefaultPersistentStoreCoordinator:(BOOL)shouldAutoCreate;
{
shouldAutoCreateDefaultPersistentStoreCoordinator_ = shouldAutoCreate;
}
#ifdef NS_BLOCKS_AVAILABLE
#pragma mark DEPRECATED_METHOD
+ (void) performSaveDataOperationWithBlock:(CoreDataBlock)block;
{
[MRCoreDataAction saveDataWithBlock:block];
}
+ (void) performSaveDataOperationInBackgroundWithBlock:(CoreDataBlock)block;
{
[MRCoreDataAction saveDataInBackgroundWithBlock:block];
}
+ (void) performLookupOperationWithBlock:(CoreDataBlock)block;
{
[MRCoreDataAction lookupWithBlock:block];
}
+ (void) performSaveDataOperationInBackgroundWithBlock:(CoreDataBlock)block completion:(void(^)(void))callback;
{
[MRCoreDataAction saveDataInBackgroundWithBlock:block completion:callback];
}
#endif
#pragma mark - Support methods for shorthand methods
#ifdef MR_SHORTHAND
+ (BOOL) MR_resolveClassMethod:(SEL)originalSelector
{
BOOL resolvedClassMethod = [self MR_resolveClassMethod:originalSelector];
if (!resolvedClassMethod)
{
resolvedClassMethod = addMagicalRecordShortHandMethodToPrefixedClassMethod(self, originalSelector);
}
return resolvedClassMethod;
}
+ (BOOL) MR_resolveInstanceMethod:(SEL)originalSelector
{
BOOL resolvedClassMethod = [self MR_resolveInstanceMethod:originalSelector];
if (!resolvedClassMethod)
{
resolvedClassMethod = addMagicalRecordShorthandMethodToPrefixedInstanceMethod(self, originalSelector);
}
return resolvedClassMethod;
}
//In order to add support for non-prefixed AND prefixed methods, we need to swap the existing resolveClassMethod: and resolveInstanceMethod: implementations with the one in this class.
+ (void) updateResolveMethodsForClass:(Class)klass
{
replaceSelectorForTargetWithSourceImpAndSwizzle(self, @selector(MR_resolveClassMethod:), klass, @selector(resolveClassMethod:));
replaceSelectorForTargetWithSourceImpAndSwizzle(self, @selector(MR_resolveInstanceMethod:), klass, @selector(resolveInstanceMethod:));
}
+ (void) swizzleShorthandMethods;
{
if (methodsHaveBeenSwizzled) return;
NSArray *classes = [NSArray arrayWithObjects:
[NSManagedObject class],
[NSManagedObjectContext class],
[NSManagedObjectModel class],
[NSPersistentStore class],
[NSPersistentStoreCoordinator class], nil];
[classes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Class klass = (Class)obj;
[self updateResolveMethodsForClass:klass];
}];
methodsHaveBeenSwizzled = YES;
}
#endif
#pragma mark - initialize
+ (void) initialize;
{
if (self == [MagicalRecordHelpers class])
{
#ifdef MR_SHORTHAND
[self swizzleShorthandMethods];
#endif
[self setShouldAutoCreateManagedObjectModel:YES];
[self setShouldAutoCreateDefaultPersistentStoreCoordinator:YES];
}
}
@end
#pragma mark - Support functions for runtime shorthand Method calling
void replaceSelectorForTargetWithSourceImpAndSwizzle(Class sourceClass, SEL sourceSelector, Class targetClass, SEL targetSelector)
{
Method sourceClassMethod = class_getClassMethod(sourceClass, sourceSelector);
Method targetClassMethod = class_getClassMethod(targetClass, targetSelector);
Class targetMetaClass = objc_getMetaClass([NSStringFromClass(targetClass) cStringUsingEncoding:NSUTF8StringEncoding]);
BOOL methodWasAdded = class_addMethod(targetMetaClass, sourceSelector,
method_getImplementation(targetClassMethod),
method_getTypeEncoding(targetClassMethod));
if (methodWasAdded)
{
class_replaceMethod(targetMetaClass, targetSelector,
method_getImplementation(sourceClassMethod),
method_getTypeEncoding(sourceClassMethod));
}
}
BOOL addMagicalRecordShorthandMethodToPrefixedInstanceMethod(Class klass, SEL originalSelector)
{
NSString *originalSelectorString = NSStringFromSelector(originalSelector);
if ([originalSelectorString hasPrefix:@"_"] || [originalSelectorString hasPrefix:@"init"]) return NO;
if (![originalSelectorString hasPrefix:kMagicalRecordCategoryPrefix])
{
NSString *prefixedSelector = [kMagicalRecordCategoryPrefix stringByAppendingString:originalSelectorString];
Method existingMethod = class_getInstanceMethod(klass, NSSelectorFromString(prefixedSelector));
if (existingMethod)
{
BOOL methodWasAdded = class_addMethod(klass,
originalSelector,
method_getImplementation(existingMethod),
method_getTypeEncoding(existingMethod));
return methodWasAdded;
}
}
return NO;
}
BOOL addMagicalRecordShortHandMethodToPrefixedClassMethod(Class klass, SEL originalSelector)
{
NSString *originalSelectorString = NSStringFromSelector(originalSelector);
if (![originalSelectorString hasPrefix:kMagicalRecordCategoryPrefix])
{
NSString *prefixedSelector = [kMagicalRecordCategoryPrefix stringByAppendingString:originalSelectorString];
Method existingMethod = class_getClassMethod(klass, NSSelectorFromString(prefixedSelector));
if (existingMethod)
{
Class metaClass = objc_getMetaClass([NSStringFromClass(klass) cStringUsingEncoding:NSUTF8StringEncoding]);
BOOL methodWasAdded = class_addMethod(metaClass,
originalSelector,
method_getImplementation(existingMethod),
method_getTypeEncoding(existingMethod));
return methodWasAdded;
}
}
return NO;
}
#pragma mark - Data import helper functions
NSString * attributeNameFromString(NSString *value)
{
NSString *firstCharacter = [[value substringToIndex:1] capitalizedString];
return [firstCharacter stringByAppendingString:[value substringFromIndex:1]];
}
NSString * primaryKeyNameFromString(NSString *value)
{
NSString *firstCharacter = [[value substringToIndex:1] lowercaseString];
return [firstCharacter stringByAppendingFormat:@"%@ID", [value substringFromIndex:1]];
}
NSDate * adjustDateForDST(NSDate *date)
{
NSTimeInterval dstOffset = [[NSTimeZone localTimeZone] daylightSavingTimeOffsetForDate:date];
NSDate *actualDate = [date dateByAddingTimeInterval:dstOffset];
return actualDate;
}
NSDate * dateFromString(NSString *value, NSString *format)
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateFormat:format];
NSDate *parsedDate = [formatter dateFromString:value];
MR_AUTORELEASE(formatter);
return parsedDate;
}
NSInteger* newColorComponentsFromString(NSString *serializedColor);
NSInteger* newColorComponentsFromString(NSString *serializedColor)
{
NSScanner *colorScanner = [NSScanner scannerWithString:serializedColor];
NSString *colorType;
[colorScanner scanUpToString:@"(" intoString:&colorType];
NSInteger *componentValues = malloc(4 * sizeof(NSInteger));
if ([colorType hasPrefix:@"rgba"])
{
NSCharacterSet *rgbaCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"(,)"];
NSInteger *componentValue = componentValues;
while (![colorScanner isAtEnd])
{
[colorScanner scanCharactersFromSet:rgbaCharacterSet intoString:nil];
[colorScanner scanInteger:componentValue];
componentValue++;
}
}
//else if ([colorType hasPrefix:@"hsba"])
//else if ([colorType hasPrefix:@""])
return componentValues;
}
#if TARGET_OS_IPHONE
UIColor * UIColorFromString(NSString *serializedColor)
{
NSInteger *componentValues = newColorComponentsFromString(serializedColor);
UIColor *color = [UIColor colorWithRed:(componentValues[0] / 255.)
green:(componentValues[1] / 255.)
blue:(componentValues[2] / 255.)
alpha:componentValues[3]];
free(componentValues);
return color;
}
id (*colorFromString)(NSString *) = UIColorFromString;
#else
NSColor * NSColorFromString(NSString *serializedColor)
{
NSInteger *componentValues = newColorComponentsFromString(serializedColor);
NSColor *color = [NSColor colorWithDeviceRed:(componentValues[0] / 255.)
green:(componentValues[1] / 255.)
blue:(componentValues[2] / 255.)
alpha:componentValues[3]];
free(componentValues);
return color;
}
id (*colorFromString)(NSString *) = NSColorFromString;
#endif