A few months ago I started using FRCoreDataOperation to serialize Core Data objects to disk. Sure you could do this with plists, but thats a little too restrictive especially if you want the serialized data to be compatible with other applications and platforms. Usually my format of choice is CSV, as you can import it into excel/ google docs easily, also python has a great module for loading CSV data.
For another project I found myself needing to do the same thing again, the classic sign that it was time to do make something reusable and adaptable. So FRCoreDataExportOperation was born. FRCoreDataExportOperation is a concrete subclass of FRCoreDataOperation and can be used without subclassing. Below is an example of how you use the class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FRCoreDataExportOperation *op = [[FRCoreDataExportOperation alloc] initWithEntityName:@"Destination" managedObjectContext:<MAIN CONTEXT>]; | |
//[Optional] Set the name of the output file | |
[op setFileName:@"output.txt"]; | |
//Set the entity formatter | |
[op setEntityFormatter:[[FRCSVEntityFormatter alloc] init]]; | |
[<YOUR OPERATION QUEUE> addOperation:op]; | |
//[Optional] Set a completion block to know when the file is complete | |
[op setCompletionBlock:^{ | |
//Refresh the UI or send a notification | |
}]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (id)initWithEntityName:(NSString *)aName | |
predicate:(NSPredicate *)aPredicate | |
sortDescriptors:(NSArray *)sortDescriptors | |
managedObjectContext:(NSManagedObjectContext *)aMOC |
The next step is to select a formatter, the actual serialization format is completely abstracted from the class and is performed by the object assigned to FRCoreDataExportOperation's entityFormatter property. Thus far i've only created the FRCoreDataEntityFormatter, FRCSVEntityFormatter, but you can create your own by implementing the FRCoreDataEntityFormatter protocol.
The FRCSVEntityFormatter is somewhat customizable, and allows you to specify a NSArray with the keypaths that you want to be serialized to disk. The columns will be written in the order they appear in the array. If you choose to use the formatter without a whitelist, all of the properties will be written in the alphabetical order of the property name.
Best of all you can get this for yourself via Cocoapods, pod is aptly called FRCoreDataOperation
Happy exporting