xcode 从 csv 文件 (iphone SDk) 加载数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2426374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:10:54  来源:igfitidea点击:

Load data from csv file (iphone SDk)

iphonexcodecsvsdk

提问by Ni.

Does anyone know how to load data from csv file?

有谁知道如何从 csv 文件加载数据?

For the code example, CPTestAppScatterPlotController.m that I downloaded from core-plot Google website, a line graph can be plotted based on randomly generated initial data x, y.

对于我从 core-plot Google 网站下载的代码示例 CPTestAppScatterPlotController.m,可以根据随机生成的初始数据 x、y 绘制折线图。

 // Add some initial data
 SMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
 NSUInteger i;
 for ( i = 0; i < 60; i++ ) {
     id x = [NSNumber numberWithFloat:1+i*0.05];
     id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_MAX + 1.2];
     [contentArray addObject:[NSMutableDictionary 
                      dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
self.dataForPlot = contentArray;

Then i modified the code,

然后我修改了代码,

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ECG_Data" ofType:@"csv"];
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil ];
NSScanner *scanner = [NSScanner scannerWithString:myText];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"\n, "]];
NSMutableArray *newPoints = [NSMutableArray array];           
float time, data;
while ( [scanner scanFloat:&time] && [scanner scanFloat:&data] ) {
    [newPoints addObject:
    [NSMutableDictionary dictionaryWithObjectsAndKeys:
            [NSNumber numberWithFloat:time], @"time",
            [NSNumber numberWithFloat:data], @"data",
             nil]];
}
self.dataForPlot = newPoints;

It seems that my code could not read the data from csv file. (there are two cols of the data in ECG_Data.csv, one for time and one for data) Can anyone give me some suggestion??? Thanks!!!!

我的代码似乎无法从 csv 文件中读取数据。(ECG_Data.csv 中有两列数据,一列用于时间,一列用于数据)谁能给我一些建议???谢谢!!!!

回答by benasher44

http://cocoawithlove.com/2009/11/writing-parser-using-nsscanner-csv.html

http://cocoawithlove.com/2009/11/writing-parser-using-nsscanner-csv.html

Here is a good place to start for creating a CSV parser. It's complete with sample code and user comments.

这是创建 CSV 解析器的好地方。它包含示例代码和用户评论。