-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFRCoreDataExportOperation.m
334 lines (238 loc) · 10.9 KB
/
FRCoreDataExportOperation.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
//
// FRCoreDataExportOperation.m
//
// Created by Jonathan Dalrymple on 11/11/2012.
//
// Copyright (C) 2012 Jonathan Dalrymple
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#import "FRCoreDataExportOperation.h"
@interface FRCoreDataExportOperation ()
@property (nonatomic,copy,readwrite) NSString *fileName;
@property (nonatomic,copy,readwrite) NSPredicate *predicate;
@property (nonatomic,copy,readwrite) NSArray *sortDescriptors;
@property (nonatomic,strong,readwrite) NSEntityDescription *entityDescription;
@end
@implementation FRCoreDataExportOperation
#pragma mark - Object creation
- (id)initWithEntityName:(NSString *)aName
managedObjectContext:(NSManagedObjectContext *)aMOC {
self = [super initWithManagedObjectContext:aMOC];
if (self) {
[self setEntityDescription:[NSEntityDescription entityForName:aName
inManagedObjectContext:aMOC]];
}
return self;
}
- (id)initWithEntityName:(NSString *)aName
predicate:(NSPredicate *)aPredicate
managedObjectContext:(NSManagedObjectContext *)aMOC {
self = [self initWithEntityName:aName
managedObjectContext:aMOC];
if (self) {
[self setPredicate:aPredicate];
}
return self;
}
- (id)initWithEntityName:(NSString *)aName
predicate:(NSPredicate *)aPredicate
sortDescriptors:(NSArray *)sortDescriptors
managedObjectContext:(NSManagedObjectContext *)aMOC {
self = [self initWithEntityName:aName
managedObjectContext:aMOC];
if (self) {
[self setPredicate:aPredicate];
[self setSortDescriptors:sortDescriptors];
}
return self;
}
#pragma mark - Formatting
- (NSString *)entityName {
return [[self entityDescription] name];
}
- (void)setEntityFormatter:(id<FRCoreDataEntityFormatter>)aFormatter {
NSAssert(![self isExecuting], @"Cannot change the operation once it has started");
_entityFormatter = nil;
_entityFormatter = aFormatter;
}
- (void)setFileName:(NSString *)aFileName {
NSAssert(![self isExecuting], @"Cannot change the operation once it has started");
_fileName = nil;
_fileName = [aFileName copy];
}
#pragma mark - Object stringification
-(id)transformValue:(id)aValue withAttributeName:(NSString *)aName {
id returnValue = [NSNull null];
//Attempt to transform value based on type where the value is not nil
if ([aValue isKindOfClass:[NSNumber class]]
&& [[self entityFormatter] respondsToSelector:@selector(transformNumberValue:withAttributeName:)] ) {
returnValue = [[self entityFormatter] transformNumberValue:aValue
withAttributeName:aName];
}
else if ([aValue isKindOfClass:[NSString class]]
&& [[self entityFormatter] respondsToSelector:@selector(transformStringValue:withAttributeName:)]) {
returnValue = [[self entityFormatter] transformStringValue:aValue
withAttributeName:aName];
}
else if ([aValue isKindOfClass:[NSDate class]]
&& [[self entityFormatter] respondsToSelector:@selector(transformDateValue:withAttributeName:)]) {
returnValue = [[self entityFormatter] transformDateValue:aValue
withAttributeName:aName];
}
else if ([aValue isKindOfClass:[NSData class]]
&& [[self entityFormatter] respondsToSelector:@selector(transformDataValue:withAttributeName:)]) {
returnValue = [[self entityFormatter] transformDataValue:aValue
withAttributeName:aName];
}
else if (aValue && [[self entityFormatter] respondsToSelector:@selector(transformValue:withAttributeName:)]) {
returnValue = [[self entityFormatter] transformValue:aValue
withAttributeName:aName];
}
else if (aValue) { //If there is no formatter and the value is not nil return as is.
returnValue = aValue;
}
//execution should only reach here is the value is nil
return returnValue;
}
- (NSDictionary *)dictionaryRepresentationOfManagedObject:(NSManagedObject *)aObject {
return [self dictionaryRepresentationOfManagedObject:aObject
recursive:YES];
}
- (NSDictionary *)dictionaryRepresentationOfManagedObject:(NSManagedObject *)aObject
recursive:(BOOL)isRecursive {
NSMutableDictionary *dictionary;
NSDictionary *attributes;
attributes = [[aObject entity] attributesByName];
dictionary = [NSMutableDictionary dictionaryWithCapacity:[attributes count]];
for (NSString *key in [attributes allKeys]) {
[dictionary setObject:[self transformValue:[aObject valueForKey:key] withAttributeName:key]
forKey:key];
}
//Append the relationships to the dictionary
if (isRecursive) {
[dictionary addEntriesFromDictionary:[self dictionaryRepresentationOfRelationshipsWithManagedObject:aObject]];
}
return [dictionary copy];
}
- (NSDictionary *)dictionaryRepresentationOfRelationshipsWithManagedObject:(NSManagedObject *)aObject {
NSDictionary *relationships = [[aObject entity] relationshipsByName];
NSDictionary *dictionary;
for (NSString *key in [relationships allKeys]) {
NSRelationshipDescription *relationship = [relationships objectForKey:key];
NSMutableArray *objects;
//Handle one to one relationships
//break the loop
if (![relationship isToMany]) {
dictionary = @{
key:[self dictionaryRepresentationOfManagedObject:[aObject valueForKey:key] recursive:NO]
};
break;
}
//Initialize the array and get the capacity
objects = [NSMutableArray arrayWithCapacity:[[aObject valueForKey:key] count]];
//Handle one to many relationships
for (NSManagedObject *obj in [aObject valueForKey:key]) {
[objects addObject:[self dictionaryRepresentationOfManagedObject:obj
recursive:NO]];
}
dictionary = @{key:objects};
}
return dictionary;
}
- (NSString *)filePath {
NSString *fileName = nil;
if (!(fileName = [self fileName])) {
fileName = [NSString stringWithFormat:@"%@.dat",[[self entityName] lowercaseString]];
}
return [NSString pathWithComponents:@[
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0],
fileName
]];
}
#pragma mark - Object formatting proxy
- (NSData *)dataForManagedObject:(NSManagedObject *)aObject {
return [[self entityFormatter] dataForDictionaryRespresentation:[self dictionaryRepresentationOfManagedObject:aObject]
ofEntity:[self entityDescription]];
}
#pragma mark - Main
- (void)main {
NSEntityDescription *entityDescription = nil;
NSFetchRequest *fetchRequest = nil;
NSFileHandle *fileHandle = nil;
NSDictionary *attributes = nil;
NSArray *results = nil;
NSError *error = nil;
@autoreleasepool {
fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setPredicate:[self predicate]];
entityDescription = [NSEntityDescription entityForName:[self entityName]
inManagedObjectContext:[self threadContext]];
NSAssert(entityDescription, @"Invalid Entity %@",[self entityName]);
[fetchRequest setEntity:entityDescription];
//Fetch all the objects within the predicate
results = [[self threadContext] executeFetchRequest:fetchRequest
error:&error];
NSLog(@"Exporting %lu %@ objects",[results count],[self entityName]);
if (!results || error) {
NSLog(@"Fetch error %@",error);
}
//Reuse the error prtr
error = nil;
///////////////////////////////
// Prepare the file for writing
///////////////////////////////
// Open a mapped NSMutableData
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:[self filePath]]) {
[fileManager removeItemAtPath:[self filePath]
error:&error];
}
[fileManager createFileAtPath:[self filePath]
contents:[NSData data]
attributes:nil];
fileHandle = [NSFileHandle fileHandleForWritingAtPath:[self filePath]];
if (!fileHandle || error ) {
NSLog(@"File error %@",error);
}
attributes = [entityDescription attributesByName];
//Header
if ([[self entityFormatter] respondsToSelector:@selector(dataForHeaderOfEntity:)]) {
[fileHandle writeData:[[self entityFormatter] dataForHeaderOfEntity:[self entityDescription]]];
}
//Exact the attribute names and print them
for (NSUInteger i=0; i < [results count]; i++) {
NSManagedObject *obj = (NSManagedObject *)[results objectAtIndex:i];
//Keep the object overhead low
@autoreleasepool {
NSData *data;
data = [[self entityFormatter] dataForDictionaryRespresentation:[self dictionaryRepresentationOfManagedObject:obj]
ofEntity:[self entityDescription]];
[fileHandle writeData:data];
//Insert the delimiter
if ( i < ([results count]-1) ) {
[fileHandle writeData:[[self entityFormatter] dataForObjectDelimiterOfEntity:[self entityDescription]]];
}
//Force the object we've just read to fault to
[[self threadContext] refreshObject:obj
mergeChanges:NO];
}
}
// Append the Footer
if ([[self entityFormatter] respondsToSelector:@selector(dataForFooterOfEntity:)]) {
[fileHandle writeData:[[self entityFormatter] dataForFooterOfEntity:[self entityDescription]]];
}
//Reuse the error prtr
error = nil;
//Close the file
[fileHandle closeFile];
if (error) {
NSLog(@"File Error %@",error);
}
}
}
@end