I've been working on an iPhone application where I needed to save some data into the SQLite database via CoreData. The data I had was in a .csv file and I needed to preload this data on to the phone. I had two choices:
- Create an SQLite database by some programmatic means and import this as the store for CoreData.
- Read the .csv file and create NSManagedObject instances which can be saved to the context.
Option 1 seemed a little more daunting for me, so I chose the second option using NSUserDefaults to save a flag that I'd already read the .csv. I'm still investigating the first option and will report back if I'm successful. Anyway, here's a sample of the contents of the file:
So that's an excerpt of the .csv - four columns of integer, double, double and a string. Including your csv file in the resources folder of your XCode project. Ensure that the "Target" checkbox is checked (Its on the top of the right content pane when the .csv file has been selected). Next is the code to load this data:
- // load the points from our local resource
- NSString* filePath = [[NSBundle mainBundle] pathForResource:@"a_csv_file" ofType:@"csv"];
- NSString* fileContents = [NSString stringWithContentsOfFile:filePath];
- NSArray* pointStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
- //NSMutableArray* points = [[NSMutableArray alloc] initWithCapacity:pointStrings.count];
- for(int idx = 0; idx < pointStrings.count; idx++)
- // break the string down even further to the columns
- NSString* currentPointString = [pointStrings objectAtIndex:idx];
- NSArray* arr = [currentPointString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
- NSNumber *colTwo = [[NSNumber alloc] initWithDouble: [[arr objectAtIndex:1] doubleValue]];
- NSNumber *colThree = [[NSNumber alloc] initWithDouble: [[arr objectAtIndex:2] doubleValue]];
- NSNumber *colOne = [[NSNumber alloc] initWithInt:[[arr objectAtIndex:0] intValue]];
- NSString *colFour = [[NSString alloc] initWithFormat:@"%@", [arr objectAtIndex:3]];
- //... we can now use these pointers to save to the CoreData database
In line 06 of the code above, we've selected a newLineCharacterSet as the delimiter so that the file is split by lines. In line 14, we then use the comma character set to split the columns by comma. Et Voila! Finally, see the rather odd way of reading strings. Must be a simpler way...