Converting CSV File to NSArray of NSDictionaries
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.
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];
}
精彩评论