开发者

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

I am using Core Data in my iPhone apps. It works fine when I use it in the simulator but when I deploy it to device, the value of my Core Data store is not found to my application. If I insert a value on the iPhone it finds the value in Core Data.

I need to keep the value of Core Data while deploying it to iPhone.

Please help me if anyone knows 开发者_JAVA百科how to do this.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜