forked from steipete/PSFoundation
/
NSManagedObjectContext+ActiveRecord.m
245 lines (216 loc) · 6.95 KB
/
NSManagedObjectContext+ActiveRecord.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
//
// NSManagedObjectContext+ActiveRecord.m
//
// Created by Saul Mora on 11/23/09.
// Copyright 2010 Magical Panda Software, LLC All rights reserved.
//
#import "NSManagedObject+ActiveRecord.h"
#import "NSManagedObjectContext+ActiveRecord.h"
#import "NSPersistentStoreCoordinator+ActiveRecord.h"
static NSManagedObjectContext *defaultManageObjectContext = nil;
@implementation NSManagedObjectContext (ActiveRecord)
+ (NSManagedObjectContext *)defaultContext
{
//NSAssert([NSThread isMainThread], @"The defaultContext must only be accessed on the **Main Thread**");
@synchronized (self)
{
if (defaultManageObjectContext)
{
return defaultManageObjectContext;
}
}
return nil;
}
+ (void) setDefaultContext:(NSManagedObjectContext *)moc
{
[defaultManageObjectContext release];
defaultManageObjectContext = [moc retain];
}
+ (void) resetDefaultContext
{
dispatch_sync(dispatch_get_main_queue(), ^{
[[NSManagedObjectContext defaultContext] reset];
});
}
+ (NSManagedObjectContext *) contextForCurrentThread
{
if ( [NSThread isMainThread] )
{
return [self defaultContext];
}
else
{
NSMutableDictionary *threadDict = [[NSThread currentThread] threadDictionary];
NSManagedObjectContext *threadContext = [threadDict objectForKey:@"MO_Context"];
if ( threadContext == nil )
{
threadContext = [self context];
[threadDict setObject:threadContext forKey:@"MO_Context"];
}
return threadContext;
}
}
- (void) observeContext:(NSManagedObjectContext *)otherContext
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(mergeChangesFromNotification:)
name:NSManagedObjectContextDidSaveNotification
object:otherContext];
}
- (void) observeContextOnMainThread:(NSManagedObjectContext *)otherContext
{
DDLogVerbose(@"Start Observing on Main Thread");
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(mergeChangesOnMainThread:)
name:NSManagedObjectContextDidSaveNotification
object:otherContext];
}
- (void) stopObservingContext:(NSManagedObjectContext *)otherContext
{
DDLogVerbose(@"Stop Observing Context");
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSManagedObjectContextDidSaveNotification
object:otherContext];
}
- (void) mergeChangesFromNotification:(NSNotification *)notification
{
DDLogInfo(@"Merging changes to context%@", [NSThread isMainThread] ? @" *** on Main Thread ***" : @"");
[self mergeChangesFromContextDidSaveNotification:notification];
}
- (void) mergeChangesOnMainThread:(NSNotification *)notification
{
if ([NSThread isMainThread])
{
[self mergeChangesFromNotification:notification];
}
else
{
[self performSelectorOnMainThread:@selector(mergeChangesFromNotification:) withObject:notification waitUntilDone:YES];
}
}
- (BOOL) save
{
NSError *error = nil;
BOOL saved = NO;
@try
{
DDLogVerbose(@"Saving Context%@", [NSThread isMainThread] ? @" *** on Main Thread ***" : @"");
saved = [self save:&error];
}
@catch (NSException *exception)
{
DDLogWarn(@"Problem saving: %@", (id)[exception userInfo] ?: (id)[exception reason]);
}
[ActiveRecordHelpers handleErrors:error];
return saved && error == nil;
}
- (void) saveWrapper
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self save];
[pool drain];
}
- (BOOL) saveOnBackgroundThread
{
[self performSelectorInBackground:@selector(saveWrapper) withObject:nil];
return YES;
}
- (BOOL) saveOnMainThread
{
@synchronized(self)
{
[self performSelectorOnMainThread:@selector(saveWrapper) withObject:nil waitUntilDone:YES];
}
return YES;
}
+ (NSManagedObjectContext *) contextWithStoreCoordinator:(NSPersistentStoreCoordinator *)coordinator
{
NSManagedObjectContext *context = nil;
if (coordinator != nil)
{
context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:coordinator];
[context setUndoManager:nil];
}
return [context autorelease];
}
+ (NSManagedObjectContext *) context
{
return [self contextWithStoreCoordinator:[NSPersistentStoreCoordinator defaultStoreCoordinator]];
}
+ (NSManagedObjectContext *) contextThatNotifiesDefaultContextOnMainThread
{
NSManagedObjectContext *context = [self context];
[[self defaultContext] observeContextOnMainThread:context];
return context;
}
- (void)logDetailedError:(NSError *)error from:(id)caller selector:(SEL)selector
{
#if DEBUG
DDLogInfo(@"*** CORE DATA ERROR: a data store operation failed");
DDLogInfo(@"*** Caller was: %@ %p %@", [caller class], caller, NSStringFromSelector(selector));
DDLogInfo(@"*** Error: %@", [error localizedDescription]);
NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
if ([detailedErrors count] > 0)
{
for(NSError* detailedError in detailedErrors)
DDLogInfo(@"> DetailedError: %@", [detailedError userInfo]);
}
else
{
DDLogInfo(@" %@", [error userInfo]);
}
#endif
}
- (void)logContextChanges
{
#if DEBUG
// Log the current changes for the context
if (![self hasChanges])
return;
DDLogInfo(@"***************************************************");
DDLogInfo(@"* CHANGES TO %@ %p", [self class], self);
DDLogInfo(@"***************************************************");
NSSet *updated = [self updatedObjects];
NSSet *inserted = [self insertedObjects];
NSSet *deleted = [self deletedObjects];
if ([updated count])
{
DDLogInfo(@"* UPDATED OBJECTS:");
for (NSManagedObject *anObject in [self updatedObjects])
{
DDLogInfo(@"* %@ %p has the following changes:", [anObject class], anObject);
NSDictionary *changedValues = [anObject changedValues];
NSArray *keys = [changedValues allKeys];
NSDictionary *oldValues = [anObject committedValuesForKeys:keys];
for (NSString *key in keys)
DDLogInfo(@" Attribute '%@' was {%@} is now {%@}", key, [oldValues objectForKey:key], [changedValues objectForKey:key]);
DDLogInfo(@"*");
}
}
if ([inserted count])
{
if ([updated count])
DDLogInfo(@"***************************************************");
DDLogInfo(@"* INSERTED OBJECTS:");
for (NSManagedObject *anObject in [self insertedObjects])
{
DDLogInfo(@"* %@", anObject);
DDLogInfo(@"*");
}
}
if ([deleted count])
{
if ([updated count] || [inserted count])
DDLogInfo(@"***************************************************");
DDLogInfo(@"* DELETED OBJECTS:");
for (NSManagedObject *anObject in [self deletedObjects])
{
DDLogInfo(@"* %@", anObject);
DDLogInfo(@"*");
}
}
DDLogInfo(@"***************************************************");
#endif
}
@end