简体   繁体   中英

iOS how to do pre-filled Core data?

I need my application work as follows:

1- User download and startup the application.

2- The application will automatically fill the (based core data) with specific records. 3- The application will works ok.

4- When the user close the application and restart it.

5_ The application will not automatically fill the core data with the specific records because it already there.

6- The user will not be able to add/remove/update the data.

Is there a good technique to do that using only core data and accepted by Apple.

  1. Populate the data in the simulator
  2. Make a copy of the SQLITE database from the simulator folder
  3. Add the database as a resource to your project.
  4. Do something like this before initializing your Core Data stack:

code:

// Put down default db if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:storePath]) {
    NSString *defaultStorePath = [[NSBundle mainBundle] 
                                  pathForResource:@"MyDataFile" ofType:@"sqlite"];
    if (defaultStorePath) {
        [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];

    }
}

Not shown, but critical: all the files you prepopulate data for must be marked as "do not backup", or you will be rejected, per the App Store guidelines. See this SO question for some details on how to do this: Why was my application still rejected after excluding files from iCloud backup using this code?

I can tell you one very easy way to do it. In the app delegate, create a variable in NSUserDefaults and change its value when the application is loaded for the first time. Then depending upon the value of NSUserDefaults, fill the data you want in the Core Data store. And this will happen only once because the value of NSUserDefaults variable is not going to change again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM