Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from CSV file and create arrays in Objective-C Xcode

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?

like image 510
Galil Avatar asked Jul 24 '14 19:07

Galil


1 Answers

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

like image 71
idmean Avatar answered Oct 23 '22 06:10

idmean