I have a picture slideshow app which allows the user to rate 3 images. The ratings get stored in a NSMutableArray called rated like this:
2014-01-06 07:10:23.040 SlideShowSurvey[50425:70b] (
1, <-- Rating for Picture 1
2, <-- Rating for Picture 2
3 <-- Rating for Picture 3
)
This is then saved to a .csv file using the following code:
-(void)saveRatings
{
NSString *picRatings = [NSString stringWithFormat:@"%@, \n",self.rated];
// Find documents directory
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *survey = [docPath stringByAppendingPathComponent:@"pictureRatings.csv"];
// Create new file if none exists
if (![[NSFileManager defaultManager] fileExistsAtPath:survey])
{
[[NSFileManager defaultManager] createFileAtPath:survey contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:survey];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[picRatings dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
}
I can then display the results of the .csv file to a UITextView, though it displays it exactly how the array is structured. For example, multiple results display as:
(
1,
2,
3
),
(
1,
2,
3
),
(
1,
2,
3
)
Is there a way I am able to format the array so that it is saved as 1,2,3? And would I be able to add a column header like Picture 1, Picture 2, Picture 3? For example, I would like to display results on the UITextView something like:
Picture 1, Picture 2, Picture 3
1,2,3
1,2,3
1,2,3
I've tried searching but can't seem to find this answer. Any help is appreciated! Thanks.
Edit: I have solved this thanks to jrturton's solution, using the following code:
// Set column titles for .csv
NSArray *columnTitleArray = @[@"Picture 1", @"Picture 2", @"Picture 3"];
NSString *columnTitle = [columnTitleArray componentsJoinedByString:@","];
NSString *columnTitleToWrite = [columnTitle stringByAppendingString:@"\n"];
// Separate ratings into cells
NSString *picRatings = [rated componentsJoinedByString:@","];
NSString *picRatingsToWrite = [picRatings stringByAppendingString:@"\n"];
// Find documents directory
..
Then adding this to the method to make sure column headers are only set when a new file is created:
// Create new file if none exists
if (![[NSFileManager defaultManager] fileExistsAtPath:survey])
{
[[NSFileManager defaultManager] createFileAtPath:survey contents:nil attributes:nil];
// Set title for new file
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:survey];
[fileHandle writeData:[columnTitleToWrite dataUsingEncoding:NSUTF8StringEncoding]];
}
..
NSMutableArrayitself, not from the .csv file. I'm quite new to Objective-C. Do you know of any code examples showing how to load a .csv into aUITableView?