views:

1005

answers:

3

Hi all, ive been creating a list app and backing it with core data. I would like to have a default list of say 10 airport items so that the user doesnt have to start from scratch. Is there any way to do this? Any help is appreciated. Thanks in advance.

A: 

Yes there is in fact the CoreDataBooks example does this, you can download the code here: sample code

Basically just create your own sqlite database and add it to resources then when the application launches simply load it like this (copied from the sample code)

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

if (persistentStoreCoordinator != nil) {
    return persistentStoreCoordinator;
}


NSString *storePath = [[self applicationDocumentsDirectory]      stringByAppendingPathComponent: @"CoreDataBooks.sqlite"];
 /*
  Set up the store.
 For the sake of illustration, provide a pre-populated default store.
 */
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if (![fileManager fileExistsAtPath:storePath]) {
  NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"CoreDataBooks"      ofType:@"sqlite"];
 if (defaultStorePath) {
 [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
 }
}

NSURL *storeUrl = [NSURL fileURLWithPath:storePath];

 NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber   numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 
  persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

 NSError *error;
 if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
  // Update to handle the error appropriately.
  NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
 exit(-1);  // Fail
}    

return persistentStoreCoordinator;
}

Hope that helps.

-Oscar

OscarMk
Im guessing ill have to know sql for this correct?
Tanner
No you don't I created mine just like you would create it using SQL Server 2005 and simply inserting the values, using SQLite Database Browser which you can get here: http://mac.softpedia.com/get/Developer-Tools/SQLite-Database-Browser.shtml
OscarMk
I believe I would like the sql browser approach better because I could add different list. Ive downloaded it. Do I just add an item, name it passport and add 9 more items and then im done?
Tanner
Yes pretty much, it is as easy to use as any other Database browser.
OscarMk
Ive never used sql before. If there all small words (passport, book) for file type would I choose text? Thanks
Tanner
I assume you have already created your database. But if not you first need to click the icon create database after (the first icon with a table icon), then you can click edit database, and make the columns of type VARCHAR (this is not in the drop down option but you can add it clicking on the...), then on the Browse Data tab you can type your data (By selecting New Record), don't forget to save when you are done.
OscarMk
Ive created a table named AirportTable. I then hit create but it said no fields were there so I made 1 field called passport. Is this all id have to do if I only want 1?
Tanner
I did the above then added a new record named "passport" saved it, then added it to the project with the code above however nothing happened
Tanner
Yes that is all you need. How are you displaying your results?, are you using a NSFetchedResultsController?, I assume the code posted and your table name match, it this correct?
OscarMk
Yes but it made the app crash saying it excited with a sqlite error.
Tanner
This answer is misleading. You can't just dump data into any old SQLite database and then load it into Core Data. Core Data has a very specific internal structure to its SQLite databases that is not documented and that you are advised not to manually write to.
Brad Larson
NSUnderlyingException = I/O error for database at /var/mobile/Applications/901D08A5-B417-44C6-AEE2-BE3D1E3B0F0A/Documents/AppSql.sqlite. SQLite error code:1, 'no such table: Z_METADATA';}This si what is in the concsole but no where did I specify a Z_METADATA table. The table is called "Airport" and I have used the code above changing from coredatabooks to airport. I just need some way of pre populating core data.
Tanner
Correct, the Z_METADATA table is one among many that must be present in your SQLite database for it to work with Core Data. Again, the structure of a Core Data database is undocumented, so the recommended approach is to generate this database using a simple Mac or iPhone application that uses the same data model as your iPhone application. See the other questions I point out in my comment on this question for more.
Brad Larson
Right, on opening the coredatabooks .sqlite there are many tables. Do you know of a way to make 10 items or a default list appear? Having the app ship with a blank list doesnt seem very attractive.
Tanner
If I do create a mac core data model and populate it, drag it over to my iphone project will it hold the list? Is this a way to go? Id rather not learn xml or such if this works. Please advise.
Tanner
This will work in fact that is how I did it on one of my applications. Although I did actually use the coredatabooks.sqlite example and modified it to what I needed in order to have the needed tables to work with Core Data. Sorry I should have suggested to base yourself on that table just as I did.
OscarMk
As long as something works im happy. How did you add items to the table? What part of it did you change?
Tanner
First Delete all Records in the ZBook Table (leave the other 2 tables intact). Then modify the table as follow:leave the first 3 columns: Z_PK (identity key), Z_ENT and Z_OPT, delete the other columns, and add the column(s) you need. Finally add the records you want.
OscarMk
Manually editing a Core Data sqlite file is just asking for pain. The ONLY recommended solution for creating a Core Data sqlite file is to create it using Core Data. Your ideal situation is to create a desktop app (which you can do in minutes) and enter the data there. You can then copy the created sqlite file into your iPhone project.
Marcus S. Zarra
If I do the desktop and add say 10 items. Will those items still be in it when I transfer?
Tanner
Also if I do it like that would there be a way to make separate list? Like 1 for the airport, 1 for shopping, 1 for school...? Thanks
Tanner
A: 

For 10 items, you can just do this within applicationDidFinishLaunching: in your delegate. Define a method, say insertPredefinedObjects, that creates and populates the instances of the entity in charge of managing your airport items, and save your context. You may either read the attributes from a file or simply hardwire them in your code. Then, call this method inside applicationDidFinishLaunching:.

unforgiven
+3  A: 

Here's the best way (and doesn't require SQL knowledge):
Create a quick Core Data iPhone app (Or even Mac app) using the same object model as your List app. Write a few lines of code to save the default managed objects you want to the store. Then, run that app in the simulator. Now, go to ~/Library/Application Support/iPhone Simulator/User/Applications. Find your application among the GUIDs, then just copy the sqlite store out into your List app's project folder.

Then, load that store like they do in the CoreDataBooks example.

Ken Aspeslagh