如何将核心数据导出为CSV

我希望使用CHCSVParser将我的Core数据导出为CSV。 我知道如何从实体中获得所有的价值,但我不知道如何写入CSV。

有谁可以教我如何写入CSV与CHCSVParser

 // Test listing all Infos from the store NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"NoteLog" inManagedObjectContext:context]; [fetchRequest setEntity:entity]; NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; for (NoteLog *noteInfo in fetchedObjects) { NSLog(@"Name: %@", noteInfo.city ); NSLog(@"Name: %@", noteInfo.country); NSLog(@"Name: %@", noteInfo.datetime); NSLog(@"Name: %@", noteInfo.notelatitude); NSLog(@"Name: %@", noteInfo.notelongtitude); NSLog(@"Name: %@", noteInfo.state); NSLog(@"Name: %@", noteInfo.text); } 

CHCSVWriter有几种构buildCSV文件的方法:

-writeField:接受一个对象并将其描述(在正确转义后)写入CSV文件。 它也会写字段分隔符(,),如果有必要的话。 您可以传递一个空string(@“”)或零来写空字段。

-writeFields:接受以逗号分隔的和以nil结尾的对象列表并将其发送到-writeField :.

-writeLine用于终止当前的CSV行。 如果您不调用-writeLine,那么您的所有CSV字段将在一行中。

-writeLineOfFields:接受以逗号分隔且以nil结尾的对象列表,将每个对象发送到-writeField :,然后调用-writeLine。

-writeLineWithFields:接受一个对象数组,将每个对象发送到-writeField :,然后调用-writeLine。

-writeCommentLine:接受一个string并将其作为CSV样式的注释写出到文件中。

除了写入文件, CHCSVWriter可以被初始化为直接写入一个NSString

像这样的东西应该为你工作。

 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); 

上面的答案似乎已被弃用,作者用另一个似乎取代了方法。 这对我有用,希望它有助于:

 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];