// sets a string to be the value of the file
NSString *sourceFileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"your filename" ofType:@"csv"] encoding:NSUTF8StringEncoding error:nil];
your string will be a multiline representation of your csv file.
// create an editable array
NSMutableArray *csvArray = [[NSMutableArray alloc] init];
// set the contents of the array to the contents of the string separated by line break
csvArray = [[sourceFile componentsSeparatedByString:@"\n"] mutableCopy];
// create a string with the value of the title / name of the "columns" by pulling the first entry of the array
NSString *keysString = [csvArray objectAtIndex:0];
your result will be @"City,Country,Latitude,Longitude"
// create an array to store the column names seperated by commas
NSArray *keysArray = [keysString componentsSeparatedByString:@","];
*your result will be (
City, <--index:0
Country, <--index:1
Latitude, <--index:2
Longitude <--index:3
)
// remove the first object in the array that is storing the column names, leaving only data left
[csvArray removeObjectAtIndex:0];
**your csvArray will now be (
Aberdeen, Scotland,57.15,-2.15 <--index:0
Adelaide, Australia,-34.91666667,138.6 <--etc…
Algiers, Algeria,36.83333333,3
Amsterdam, Netherlands,52.36666667,4.883333333
Ankara, Turkey,39.91666667,32.91666667
)
// create an editable dictionary to store final data
NSMutableDictionary *outputDict = [[NSMutableDictionary alloc]init];
// create a while loop to keep track of the amount of items in the csvArray
// a "nil" value is always the last item in an array or dictionary hence the value of 1 and not 0
// 1 would essentially be an "empty" array or dictionary
while (csvArray.count > 1)
{
// create a string to store each line of info from the first item in the array
NSString *tempString = [csvArray objectAtIndex:0];
your first result would be @"Aberdeen, Scotland,57.15,-2.15"
this will change for every sequence of the loop
// create an array to store those items seperated by a comma
NSArray *tempArray = [tempString componentsSeparatedByString:@","];
your first result would be (
Aberdeen,
Scotland,
57.15,
-2.15
)
// creates a temp dictionary to store the contents of the tempArray with key values of the column names stored in keysArray
NSDictionary *tempDictionary = [[NSDictionary alloc]initWithObjects:tempArray forKeys:keysArray];
your result would be {
Aberdeen = City;
Scotland = Country;
57.15 = Latitude;
-2.15 = Longitude;
}
// adds the tempDictionary to the master dictionary with a key value of the city name that was parsed
// from the tempArray (see *)
[outputDict setObject:tempDictionary forKey:[tempArray objectAtIndex:0]];
// removes the first item in the array (the first "row" of the csv) which bumps the next line in the array up to index 0 (see **)
[csvArray removeObjectAtIndex:0];
// will repeat and remove one row at a time until the "master dictionary" is filled with a each "city" dictionary
}