Question

I have a core data app that displays its data in a tableView. I know how to create a CSV file, and I am using the following code in cellForRowAtIndexPath while my table is being created:

outputStringToCSV = [outputStringToCSV stringByAppendingFormat:@"%@ ,%@ ,%@ \n", punchitem.punchitemRoomNumber, punchitem.punchitemRoomName, punchitem.punchitemDescription];

NSLog(@"=== OUTPUTSTRING: %@", outputStringToCSV);

My outputStringToCSV is a NSString and my intent is to save the formatted string to a CSV file.

The problem is every time the tableView reloads when information or a predicate is changed, the size of the outputStringToCSV gets appended and bigger and bigger with repeated information. Should my outputStringToCSV go somewhere else other than cellForRowAtIndexPath? Is there some better way to collect the info from my table and load it into a CSV file?

I'm not sure what direction to go now and would appreciate any help. Thanks!

Was it helpful?

Solution

cellForRowAtIndexPath: should only give back the the requested cell and do nothing else. Your data will not be complete if you create the CSV file inside of that method because that method will only be called for the visible cells. If you have 1000 entries and your user never scrolls to the bottom, your file will be incomplete.

You should create a designated method to export your CSV, like so:

- (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"];
}

Done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top