I am trying to load a .csv file to Xcode using Objective-C and then I want to create two different arrays. The first array should have values from the first 2 columns and the second array the values of the third column.
I know that what I am looking for is fairly similar to this question, but I am completely newbie in Objective-C and I am a bit confused.
Until now I have tried writing the following code:
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:@","];
}
So, is this piece of code correct until now? Also, how can I divide columns into 2 different arrays in the way I described above?
Your code seems correct. But it's better to use Cocoa Fast Enumeration instead of a for loop with integers.
To divide into arrays your code could look like this.
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]];
}
Read more about NSMutableArray
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With