How to export Core Data entity to a CSV file

11,554

You have to create a method to do this kind of operation, like this:

NSString *separator = @", ";
NSString *cvs = @"";
for (NSObject *object in arrayOfObject) {
        cvs = [NSString stringWithFormat:@"%@%@%@%@%@\n", cvs, [object att1], separator, [object att2], separator, [object att3]...];
}
//If you want to store in a file the CVS
[cvs writeToFile:pathToFile atomically:YES];

I suggest you to try to avoid the "appending" system that I'm using, this kind of operation generate leaks in memory. Instead of a stringWithFormat that rewrite the same var, use this method that has been very well written: Shortcuts in Objective-C to concatenate NSStrings

You can also take a look at this library: https://github.com/davedelong/CHCSVParser I never used it, but it looks very helpful for write/read CVS files.

Share:
11,554
matteodv
Author by

matteodv

Mac User and Official iOS Developer Currently Graduate Student @ Alma Mater Studiorum - University of Bologna Knowledge iOS SDK, Swift, Objective-C, C/C++, Python, Bash HTML, CSS, JavaScript, NodeJS Website: http://www.matthewlabs.com Twitter: @matteodv Careers 2.0: http://careers.stackoverflow.com/matteodelvecchio LinkedIn: http://www.linkedin.com/in/matteodelvecchio

Updated on June 04, 2022

Comments

  • matteodv
    matteodv almost 2 years

    I'd like to be able to export my Core Data entity to a CSV file, to save application's data. I googled but found nothing.

    My app uses only one entity with five attributes. These attributes are all strings except one that is a decimal number (with a comma or a point). How can I export this entity with all the attributes?

  • matteodv
    matteodv over 13 years
    Thanks for your answer! I'll try this method and I'll see the linked parser ;) One question: must I declare "arrayOfObject"? I rarely use for construct and I've got some answers about it :)
  • bontoJR
    bontoJR over 13 years
    yes, the arrayOfObject is the array of objects that you request from Core Data.
  • matteodv
    matteodv over 13 years
    How can I get an array from Core Data? I'm using attributes without an array but with this code... For example my entity's name is Entity then I use Entity.attribute... I really don't understand how... :( Can you help me to clarify my ideas? Thanks!
  • bontoJR
    bontoJR over 13 years
    ok, that's correct to export a single entity to a single line of the CVS file that you want to generate. But before do that, you should export all entities that you've stored in you Core Data DB.
  • Neal L
    Neal L over 13 years
    You're on the right track with the CHCSVParser class. I've used it and it is awesome.