我正在尝试使用Objective-C将.csv文件加载到Xcode,然后我想创建两个不同的数组.第一个数组应该具有前2列的值,第二个数组应该具有第三列的值.
我知道我所寻找的与这个问题非常相似,但我在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:@","];
}
Run Code Online (Sandbox Code Playgroud)
那么,这段代码到现在为止是否正确?另外,我怎样才能按照上面描述的方式将列分成2个不同的数组?
idm*_*ean 11
你的代码似乎是对的.但最好使用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]];
}
Run Code Online (Sandbox Code Playgroud)
阅读更多关于NSMutableArray的信息