我有一个核心数据应用程序,它在 tableView 中显示其数据。我知道如何创建 CSV 文件,并且在创建表时在 cellForRowAtIndexPath 中使用以下代码:
outputStringToCSV = [outputStringToCSV stringByAppendingFormat:@"%@ ,%@ ,%@ \n", punchitem.punchitemRoomNumber, punchitem.punchitemRoomName, punchitem.punchitemDescription];
NSLog(@"=== OUTPUTSTRING: %@", outputStringToCSV);
我的 outputStringToCSV 是一个 NSString,我的目的是将格式化的字符串保存到 CSV 文件中。
问题是每次当信息或谓词发生变化时重新加载 tableView 时,outputStringToCSV 的大小都会随着重复信息的增加而变得越来越大。我的 outputStringToCSV 应该转到 cellForRowAtIndexPath 以外的其他地方吗?有没有更好的方法从我的表中收集信息并将其加载到 CSV 文件中?
我不确定现在该往哪个方向走,如果有任何帮助,我将不胜感激。谢谢!
最佳答案
cellForRowAtIndexPath:
应该只返回请求的单元格,不做任何其他事情。如果您在该方法内创建 CSV 文件,您的数据将不完整,因为该方法只会为可见单元格调用。如果您有 1000 个条目并且您的用户从不滚动到底部,则您的文件将不完整。
您应该创建一个指定的方法来导出您的 CSV,如下所示:
- (void)exportCSV
{
NSMutableArray *results = [[NSMutableArray alloc] init];
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"PunchItem" inManagedObjectContext:moc]];
[request setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"punchitemRoomNumber" ascending:YES]]];
NSError *error = nil;
NSArray *punchItems = [moc executeFetchRequest:request error:&error];
if (error) {
NSLog(@"Error fetching the punch item entities: %@", error);
} else {
for (PunchItem *punchitem in punchItems) {
[results addObject:[NSString stringWithFormat:@"%@ ,%@ ,%@", punchitem.punchitemRoomNumber, punchitem.punchitemRoomName, punchitem.punchitemDescription]];
}
}
NSString *resultString = [results componentsJoinedByString:@" \n"];
}
完成。
关于ios - 使用 Core Data 创建 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22670363/