Core Data: Persistent Store Works in Xcode but not on Device

2 Solutions Collect From Internet About “Core Data: Persistent Store Works in Xcode but not on Device”

It’s quite easy …

  • prepare your CoreData database file
  • name it, InitialData.sqlite for example
  • add it to your application bundle

… and add something like to this just before NSPersistentStoreCreation allocation & initialization.

NSString *storePath = ... your store path for persistent store coordinator ...;

NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:storePath]) {
  NSString *initialStorePath = [[NSBundle mainBundle] pathForResource:@"InitialData" ofType:@"sqlite"];
  if (defaultStorePath) {
    [fileManager copyItemAtPath:initialStorePath toPath:storePath error:NULL];
  }
}

I assume you want to copy some default data to your application. That’s all I can deduce from your question – it’s quite unclear what you really want.

All files including with the app install on device must be in the unalterable app bundle which makes the files readonly.

If you include a Core Data persistent store file with the app, it resides inside the app bundle and can only be added to the persistent store coordinator as as a readonly store. Any attempt to write to it will produce an error.

You usually do need a readwrite store so the solution is to use standard file operations to copy the included persistent store file from the app bundle and then into the app’s Documents or Library folder. When the app launches, the app delegate checks for the presence of the store before initializing the Core Data stack and copies it over if it hasn’t already done so.

You also have the more advanced option of using two stores for one stack, one readonly and another readwrite. However, that method introduce complexity into the data model and is usually not needed.