I am also pretty new to CoreData and have been looking for a solution for this. I was happy to find an article here: http://iphoneinaction.manning.com/iphone_in_action/core-data on how to get a CSV file and import your data (look at Core Data, Part 5: Prefilling data).
Here is the code I'm using:
-(void)addData { NSString *paths = [[NSBundle mainBundle] resourcePath]; NSString *bundlePath = [paths stringByAppendingPathComponent:@"file.csv"]; NSString *dataFile = [[NSString alloc] initWithContentsOfFile:bundlePath]; NSArray *dataRows = [dataFile componentsSeparatedByString:@"\n"]; [dataFile release]; MyEntity *myMO;
for (int i = 0 ; i < [dataRows count] ; i++) { NSLog(@"Added: %d",i); myMO = (MyEntity *)[NSEntityDescription insertNewObjectForEntityForName:@"MyEntity" inManagedObjectContext:[self managedObjectContext]]; [myMO setAttrib1:[NSNumber numberWithInt:i+1]]; [myMO setAttrib2:[dataRows objectAtIndex:i]]; [self saveAction]; } }
I only had one column, so I don't need all the code. Here is the code from the article. If that doesn't make sense, try a look at the article.
CSV file:
1,A$20,Australian Dollars,20,aussie-20.png 2,R$20,Brazilian Reals,20,brasil-20.png
the code:
- (void)setupCards { NSString *paths = [[NSBundle mainBundle] resourcePath]; NSString *bundlePath = [paths stringByAppendingPathComponent:@"cards.csv"]; NSString *dataFile = [[NSString alloc] initWithContentsOfFile:bundlePath]; NSArray *dataRows = [dataFile componentsSeparatedByString:@"\n"]; [dataFile release]; Card *card; for (int i = 0 ; i < [dataRows count] ; i++) { NSArray *dataElements = [[dataRows objectAtIndex:i] componentsSeparatedByString:@","]; if ([dataElements count] >= 4) { card = (Card *)[NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:[self managedObjectContext]]; [card setId:[NSNumber numberWithInt:i]]; [card setName:[dataElements objectAtIndex:1]]; [card setType:[dataElements objectAtIndex:2]]; [card setWorth:[NSNumber numberWithInt: [[dataElements objectAtIndex:3] intValue]]]; [card setImages:[NSSet setWithObject: [self setupCardPic:[dataElements objectAtIndex:4]]]]; [self saveAction:self]; } } }
To answer your comment: no i want to add data manually, similar to what we do in sqlite through terminal or in sql server using sql query . Download FireFox and find the Add-On tool named SQLITE MANAGER . This will allow you to open any SQLITE database, even created by your application. SQLITE MANAGER is a GUI for SQLITE databases, similar to MS SQL Server Management Studio with less features. You can view, edit and add data through it, WHAT I recommend to CONTINUE ADD data with this tool if you intend to use your database through Core Data. You can even use this tool for SQLITE databases that you usually create through Terminal (this is what I do when it is needed, and when you do not need to use MS SQL).
Rolyrolls
source share