格式化.csv文件的NSMutableArray的内容

时间:2014-01-06 07:27:44

标签: ios objective-c csv nsmutablearray uitextview

我有一个图片幻灯片应用程序,允许用户评价3张图片。评分存储在名为NSMutableArray的{​​{1}}中,如下所示:

rated

然后使用以下代码将其保存到.csv文件:

    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
)

然后我可以将.csv文件的结果显示给UITextView,尽管它显示了数组的结构。例如,多个结果显示为:

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

有没有办法可以格式化数组,使其保存为1,2,3?我能否添加如图1,图2,图3的列标题?例如,我想在UITextView上显示结果:

(
    1,
    2,
    3 
),
(
    1,
    2,
    3 
),
(
    1,
    2,
    3 
)

我试过搜索但似乎找不到这个答案。任何帮助表示赞赏!感谢。

编辑:我已经用jrturton的解决方案解决了这个问题,使用以下代码:

Picture 1, Picture 2, Picture 3
1,2,3
1,2,3
1,2,3

然后将此添加到方法中以确保仅在创建新文件时设置列标题:

        // 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
..

3 个答案:

答案 0 :(得分:1)

这是一种更简单的方法:

NSMutableString *csv = [NSMutableString string];

NSString *label = ...;

[csv appendFormat:@"%@,\n", label];

NSNumber *keyNum = ...;

[csv appendFormat:@"%d,%d\n", [keyNum intValue], [countNum intValue]];

NSString *filename = @"counts.csv";

NSError *error; 

[csv writeToFile:filename atomically:YES encoding:NSUTF8StringEncoding error:&error];

答案 1 :(得分:0)

使用此解析器并将数据导入数组,并查看如何将数据用于UITabelViewCell https://github.com/davedelong/CHCSVParser

答案 2 :(得分:0)

NSMutableString *csv = [NSMutableString string];

NSString *label = @"\n";

[csv appendFormat:@",", label];

NSString *picRatings = [rated componentsJoinedByString:csv];

我不确定您希望appendFormat在上述代码中做什么,这可能会引发警告,因为label未被使用。在这种情况下,您也不需要可变字符串。

要以逗号分隔数组内容,请执行以下操作:

NSString *picRatings = [rated componentsJoinedByString:@","];

您还需要在此字符串的末尾添加一个新行,因此您需要:

NSString *picRatingsToWrite = [picRatings stringByAppendingString:@"\n"];

将此字符串写入您的文件,您应该没问题。