2

I have a CSV file with data structured as follows:

40.697776,-73.973605,"1 CARLTON AVENUE, BROOKLYN, NEW YORK,"

40.812784,-73.952996,"1 CONVENT AVENUE, MANHATTAN, NEW YORK,"

I would like to convert each row into an NSDictionary with an NSArray holding all of the dictionaries. I would like the keys for be latitude, longitude, address.

I am new to objective c so I'm have some issues figuring this out. Any help would be greatly appreciated.

weber
  • 567
  • 1
  • 6
  • 14

1 Answers1

4

There's nothing that will do it automatically. You'll need to use an existing csv parser or write your own. Start with an empty NSMutableArray, then loop through every row in the CSV file. For each row, start with an NSMutableDictionary and add the values one at a time. When the row is finished, add the NSMutableDictionary to the end of the NSMutableArray. The code would look something like below, but the it really depends on which CSV parser you use:

NSMutableArray* allRows = [NSMutableArray array];

//how this loop is actually done depends on your CSV parser
//if it's a SAX style parser, then it won't even be a loop, it will be a callback
for(every row in the CSV file) { 
   //how you get these three fields also depends on your CSV parser
   NSNumber* firstField = ?; 
   NSNumber* secondField = ?; 
   NSString* thirdField = ?; 

   NSMutableDictionary* row = [NSMutableDictionary dictionary];
   [row setObject:firstField forKey:@"latitude"];
   [row setObject:secondField forKey:@"longitude"];
   [row setObject:thirdField forKey:@"address"];
   [allRows addObject:row];
}
Tom Dalling
  • 23,305
  • 6
  • 62
  • 80
  • But if you're like me, you'd probably want to go check out @DaveDeLong's CSV parser [here](http://stackoverflow.com/questions/3344628/where-can-i-find-a-csv-to-nsarray-parser-for-objective-c) – Mazyod Jun 05 '13 at 16:09
  • 1
    @Mazyod which Tom linked to in his answer ;) – Dave DeLong Jun 05 '13 at 16:12