Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an Array From a CSV File Using Objective C

I'm new to coding so please excuse me if this seems like a simple question.

I'm trying to plot coordinates on a map.

I want to read a CSV file and pass the information to two separate arrays.

The first array will be NSArray *towerInfo (containing latitude, longitude and tower title)

the second, NSArray *region (containing tower title and region) with the same count index as the first array.

Essentially, I believe I need to;

1) read the file to a string.....

2) divide the string into a temporary array separating at every /n/r......

3) loop through the temp array and create a tower and region object each time before appending this information to the two main storage arrays.

Is this the right process and if so is there anyone out there who can post some sample code as I'm really struggling to get this right.

Thanks to all in advance.

Chris.

I have edited this to show an example of my code. I am having the problem that I'm receiving warnings saying

1) "the local declaration of 'dataStr' hides instance variable. 2) "the local declaration of 'array' hides instance variable.

I think I understand what these mean but I don't know how to get around it. The program compiles and runs but the log tells me that the "array is null."

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize dataStr;
@synthesize array;

-(IBAction)convert {
//calls the following program when the onscreen 'convert' button is pressed.

    NSString *dataStr = [NSString stringWithContentsOfFile:@"Towers.csv" encoding:NSUTF8StringEncoding error:nil];
    //specifies the csv file to read - stored in project root directory - and encodes specifies that the format of the file is NSUTF8. Choses not to return an error message if the reading fails

    NSArray *array = [dataStr componentsSeparatedByString: @","];
    //splits the string into an array by identifying data separators.

    NSLog(@"array: %@", array);
    //prints the array to screen

}

Any additional help would be much appreciated. Thanks for the responses so far.

like image 749
user1341967 Avatar asked Apr 18 '12 16:04

user1341967


1 Answers

NSString* fileContents = [NSString stringWithContentsOfURL:filename ...];
NSArray* rows = [fileContents componentsSeparatedByString:@"\n"];
for (...
    NSString* row = [rows objectAtIndex:n];
    NSArray* columns = [row componentsSeparatedByString:@","];
...

You'll probably want to throw in a few "stringTrimmingCharactersInSet" calls to trim whitespace.

like image 67
Hot Licks Avatar answered Oct 12 '22 13:10

Hot Licks