forked from jerrykrinock/CategoriesObjC
/
NSManagedObjectContext+Cheats.m
349 lines (309 loc) · 10.5 KB
/
NSManagedObjectContext+Cheats.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
#import "NSManagedObjectContext+Cheats.h"
#import "NSArray+SafeGetters.h"
#import "NSManagedObjectModel+Versions.h"
#import "NSString+MorePaths.h"
#import "NSObject+MoreDescriptions.h"
#import "NSObject+DoNil.h"
#import "NSFileManager+SomeMore.h"
NSString* const SSYManagedObjectContextCheatsErrorDomain = @"SSYManagedObjectContextCheatsErrorDomain" ;
@implementation NSManagedObjectContext (Cheats)
- (NSPersistentStore*)store1 {
NSArray* stores = [[self persistentStoreCoordinator] persistentStores] ;
NSPersistentStore* store = [stores firstObjectSafely] ;
return store ;
}
- (NSString*)path1 {
return [[[self store1] URL] path] ;
}
+ (NSManagedObjectContext*)contextForSqlFilename:(NSString*)sqlFilename
momdName:(NSString*)momdName
modelVersionName:(NSString*)versionName
brutally:(BOOL)brutally
error_p:(NSError**)error_p {
NSString* errorDescription = nil ;
NSInteger errorCode = 0 ;
NSManagedObjectContext* managedObjectContext = nil ;
NSManagedObjectModel* mom = [NSManagedObjectModel managedObjectModelWithMomdName:momdName
versionName:versionName] ;
if (!mom) {
errorDescription = [NSString stringWithFormat:
@"Could not find managed object model %@ in %@",
versionName,
momdName] ;
errorCode = 613201 ;
goto end ;
}
NSPersistentStoreCoordinator* coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom] ;
[coordinator autorelease] ;
if (!coordinator) {
errorDescription = [NSString stringWithFormat:
@"Could not create persistent store coordinator for %@",
versionName] ;
errorCode = 613202 ;
goto end ;
}
sqlFilename = [sqlFilename stringByAppendingPathExtension:@"sql"] ;
NSString* path = [[NSString applicationSupportFolderForThisApp] stringByAppendingPathComponent:sqlFilename] ;
NSURL* url = [NSURL fileURLWithPath:path] ;
if (!url) {
errorDescription = [NSString stringWithFormat:
@"Could not create url for store %@",
sqlFilename] ;
errorCode = 613203 ;
goto end ;
}
NSDictionary* options = nil ;
if (!versionName) {
options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
nil] ;
}
NSError* error = nil ;
NSPersistentStore* persistentStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:url
options:options
error:&error] ;
if (!persistentStore) {
if (brutally) {
// Move the corrupt file, with one or more "#" appended to name.
NSString* corruptPath = [path hashifiedPath] ;
BOOL stealthOk = [[NSFileManager defaultManager] moveItemAtPath:path
toPath:corruptPath
error:&error] ;
if (!stealthOk) {
// Try to delete the damned thing
BOOL ok = [[NSFileManager defaultManager] removeItemAtPath:path
error:&error] ;
if (!ok) {
errorDescription = [NSString stringWithFormat:
@"Could not delete corrupt store %@",
path] ;
errorCode = 613204 ;
goto end ;
}
}
// Make a new one
persistentStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:url
options:options
error:&error] ;
if (!persistentStore) {
errorDescription = [NSString stringWithFormat:
@"Could not replace corrupt store %@",
url] ;
errorCode = 613205 ;
goto end ;
}
}
else {
errorDescription = [NSString stringWithFormat:
@"Could not create store %@",
url] ;
errorCode = 613206 ;
goto end ;
}
}
managedObjectContext = [[[NSManagedObjectContext alloc] init] autorelease] ;
[managedObjectContext setPersistentStoreCoordinator:coordinator] ;
[managedObjectContext setMergePolicy:NSOverwriteMergePolicy] ;
[managedObjectContext setUndoManager:nil] ;
end:
if ((errorCode != 0) && error_p) {
*error_p = [NSError errorWithDomain:SSYManagedObjectContextCheatsErrorDomain
code:errorCode
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
errorDescription, NSLocalizedDescriptionKey,
error, NSUnderlyingErrorKey, // may be nil
nil]] ;
}
return managedObjectContext ;
}
- (NSManagedObject*)singularObjectOfEntityName:(NSString*)entityName
predicate:(NSPredicate*)predicate
findings_p:(NSInteger*)findings_p {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init] ;
NSError* error = nil ;
NSArray* fetchResults = nil ;
@try {
NSEntityDescription* entity = [NSEntityDescription entityForName:entityName
inManagedObjectContext:self] ;
[fetchRequest setEntity:entity] ;
if (predicate) {
[fetchRequest setPredicate:predicate] ;
}
fetchResults = [self executeFetchRequest:fetchRequest
error:&error] ;
}
@finally {
}
[fetchRequest release];
NSManagedObject* object = nil ;
NSInteger n = [fetchResults count] ;
if (n == 1) {
object = [fetchResults objectAtIndex:0] ;
}
else if (n < 1) {
object = [NSEntityDescription insertNewObjectForEntityForName:entityName
inManagedObjectContext:self] ;
}
else {
for (NSInteger i=0; i<[fetchResults count]; i++) {
NSManagedObject* anObject = [fetchResults objectAtIndex:i] ;
[self deleteObject:anObject] ;
}
}
if (findings_p) {
*findings_p = n ;
}
return object ;
}
- (NSCountedSet*)contentSummary {
NSCountedSet* countedSet = [[NSCountedSet alloc] init] ;
for (NSManagedObject* object in [self registeredObjects]) {
NSString* entityName = [[object entity] name] ;
[countedSet addObject:entityName] ;
}
return [countedSet autorelease] ;
}
- (void)logContentSummaryWithPreface:(NSString*)preface {
NSCountedSet* countedSet = [self contentSummary] ;
NSString* msg = @"Contents of moc" ;
NSString* path = [[[self store1] URL] path] ;
if (path) {
msg = [msg stringByAppendingFormat:
@" at %@",
path] ;
}
if (preface) {
msg = [preface stringByAppendingFormat:
@": %@",
msg] ;
}
NSLog(@"%@", msg) ;
NSLog(@"%@", countedSet) ;
}
- (NSDictionary*)metadata1 {
return [[self store1] metadata] ;
}
- (id)metadata1ObjectForKey:(id)key {
return [[self metadata1] objectForKey:key] ;
}
- (void)setMetadata1Object:(id)object
forKey:(id)key {
NSMutableDictionary* metadata = [[self metadata1] mutableCopy] ;
[metadata setObject:object
forKey:key] ;
NSPersistentStoreCoordinator* persistentStoreCoordinator = [self persistentStoreCoordinator] ;
NSPersistentStore* persistentStore = [self store1] ;
if (persistentStore) {
[persistentStoreCoordinator setMetadata:metadata
forPersistentStore:persistentStore] ;
}
else {
NSError* error = [NSError errorWithDomain:SSYManagedObjectContextCheatsErrorDomain
code:315644
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
@"Could not get store", NSLocalizedDescriptionKey,
nil]] ;
NSLog(@"Internal Error in %s: %@", __PRETTY_FUNCTION__, error) ;
}
[metadata release] ;
}
- (BOOL)addMetadata1:(NSDictionary*)moreMetadata {
BOOL didDoAnything = NO ;
NSDictionary* oldMetadata = [self metadata1] ;
NSMutableDictionary* metadata = [oldMetadata mutableCopy] ;
[metadata addEntriesFromDictionary:moreMetadata] ;
if (![metadata isEqualToDictionary:oldMetadata]) {
[[self store1] setMetadata:metadata] ;
didDoAnything = YES ;
}
[metadata release] ;
return didDoAnything ;
}
- (BOOL)trashStore1Error_p:(NSError**)error_p {
NSURL* storeUrl = [[self store1] URL] ;
NSString* path = [storeUrl path] ;
NSError* error = nil ;
BOOL ok = [[NSFileManager defaultManager] trashPath:path
error_p:&error] ;
return ok ;
}
- (NSManagedObject*)objectWithUri:(NSString*)uri {
NSPersistentStoreCoordinator* psc = [self persistentStoreCoordinator] ;
NSURL* url = [NSURL URLWithString:uri] ;
NSManagedObjectID* objectId = [psc managedObjectIDForURIRepresentation:url] ;
NSManagedObject* object ;
if (objectId) {
// Prior to BookMacster 1.9.3, we just did this here:
// object = [self objectWithID:objectId] ;
// That sometimes caused Core Data exceptions as explained below.
if ([self respondsToSelector:@selector(existingObjectWithID:error:)]) {
// Mac OS X 10.6 or later
NSError* error = nil ;
object = [self existingObjectWithID:objectId
error:&error] ;
// If asking this method for nonexistent objects is expected
// behavior, you should delete this…
if (error) {
NSLog(@"Warning 927-4139 (not really an error) : %@", error) ;
}
}
else {
// Mac OS X 10.5 or earlier
object = [self objectWithID:objectId] ;
// If an object with objectId does not exist in the store, -objectWithID: will
// "helpfully" create a bogus object which will raise a "Core Data could not
// fulfill a fault" exception when we try to access any of its properties.
// (This behavior is per documentation.)
// The solution to this problem is to immediately test the object by
// trying to access one of its properties in a @try/catch block and
// catching the "Core Data could not fulfill a fault" exception.
// Amazingly, I tested this kludge and it actually worked, 3 times!
id value = nil ;
@try {
NSDictionary* attributes = [[object entity] propertiesByName] ;
NSArray* keys = [attributes allKeys] ;
NSString* aKey = [keys firstObjectSafely] ;
value = [object valueForKey:aKey] ;
}
@catch (NSException* exception) {
// If asking this method for nonexistent objects is expected
// behavior, you should delete the next line…
NSLog(@"Warning 927-6429 %@ : %@", exception, value) ;
object = nil ;
}
@finally {
}
}
}
else {
object = nil ;
}
return object ;
}
/*
// This method is not needed since -updatedObjects already behaves this way.
- (NSSet*)updatedObjectsReally {
NSMutableSet* updatedObjectsReally = [[NSMutableSet alloc] init] ;
for (NSManagedObject* object in [self updatedObjects]) {
NSDictionary* newValuesDic = [object changedValues] ;
NSDictionary* oldValuesDic = [object committedValuesForKeys:[newValuesDic allKeys]] ;
BOOL isChanged = NO ;
for (NSString* key in newValuesDic) {
isChanged = ![NSObject isEqualHandlesNilObject1:[newValuesDic objectForKey:key]
object2:[oldValuesDic objectForKey:key]] ;
if (isChanged) {
[updatedObjectsReally addObject:object] ;
//break ;
}
}
}
NSSet* answer = [NSSet setWithSet:updatedObjectsReally] ;
[updatedObjectsReally release] ;
return answer ;
}
*/
@end