从CSV文件中读取并在Objective-C Xcode中创建数组

时间:2014-07-24 19:15:30

标签: objective-c csv

我正在尝试使用Objective-C将.csv文件加载到Xcode,然后我想创建两个不同的数组。第一个数组应该包含前2列的值,第二个数组应该包含第三列的值。

我知道我所寻找的与question非常相似,但我在Objective-C中完全是新手,我有点困惑。

到目前为止,我已尝试编写以下代码:

NSString* fileContents = [NSString stringWithContentsOfURL:@"2014-07-16_15_41_20.csv"];
NSArray* rows = [fileContents componentsSeparatedByString:@"\n"];
for (int i = 0; i < rows.count; i ++){
     NSString* row = [rows objectAtIndex:i];
     NSArray* columns = [row componentsSeparatedByString:@","];
}

那么,这段代码到现在为止是否正确?另外,我怎样才能按照上面描述的方式将列分成2个不同的数组?

1 个答案:

答案 0 :(得分:8)

您的代码似乎正确无误。但最好使用Cocoa Fast Enumeration而不是带整数的for循环。

要划分为数组,您的代码可能如下所示。

NSMutableArray *colA = [NSMutableArray array];
NSMutableArray *colB = [NSMutableArray array];
NSString* fileContents = [NSString stringWithContentsOfURL:@"2014-07-16_15_41_20.csv"];
NSArray* rows = [fileContents componentsSeparatedByString:@"\n"];
for (NSString *row in rows){
     NSArray* columns = [row componentsSeparatedByString:@","];
     [colA addObject:columns[0]];
     [colB addObject:columns[1]];
}

详细了解NSMutableArray