how to export Core Data to CSV

后端 未结 2 533
天命终不由人
天命终不由人 2020-12-14 04:49

I will like to use CHCSVParser to export my Core data to CSV. I know how to get all the value from entity, but I don\'t know how to write to CSV.

Can an

相关标签:
2条回答
  • 2020-12-14 05:23

    A CHCSVWriter has several methods for constructing CSV files:

    -writeField: accepts an object and writes its -description (after being properly escaped) out to the CSV file. It will also write field seperator (,) if necessary. You may pass an empty string (@"") or nil to write an empty field.

    -writeFields: accepts a comma-delimited and nil-terminated list of objects and sends each one to -writeField:.

    -writeLine is used to terminate the current CSV line. If you do not invoke -writeLine, then all of your CSV fields will be on a single line.

    -writeLineOfFields: accepts a comma-delimited and nil-terminated list of objects, sends each one to -writeField:, and then invokes -writeLine.

    -writeLineWithFields: accepts an array of objects, sends each one to -writeField:, and then invokes -writeLine.

    -writeCommentLine: accepts a string and writes it out to the file as a CSV-style comment.

    In addition to writing to a file, CHCSVWriter can be initialized for writing directly to an NSString.

    Something Like this should work for you.

    CHCSVWriter *writer = [[CHCSVWriter alloc] initForWritingToString];
    
    for (NoteLog *noteInfo in fetchedObjects) {
    
        [writer writeLineOfFields:noteInfo.city, noteInfo.country, noteInfo.datetime, noteInfo.notelatitude, noteInfo.notelongtitude, noteInfo.state, noteInfo.text, nil];     
    }  
    
    NSLog(@"My CSV File: %@",writer.stringValue);
    
    0 讨论(0)
  • 2020-12-14 05:45

    The answer above seems to be deprecated, the author replaced the method with another it seem. This worked for me, hope it helps:

    NSOutputStream *stream = [[NSOutputStream alloc] initToMemory];
    CHCSVWriter *writer = [[CHCSVWriter alloc] initWithOutputStream:stream encoding:NSUTF8StringEncoding delimiter:','];
    
    for (Type *instance in fetchedResults) {
        [writer writeLineOfFields:@[instance.propertyA, instance.B]];
    }
    [writer closeStream];
    
    NSData *buffer = [stream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
    NSString *output = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding];
    
    0 讨论(0)
提交回复
热议问题