iOS CoreData数据迁移

http://blog.csdn.net/worldzhy/article/details/50323349

Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)"

The model used to open the store is incompatible with the one used to create the store

先推荐几篇文章:

http://www.tuicool.com/articles/B3YNNj

http://objccn.io/issue-4-7/

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/Introduction.html#//apple_ref/doc/uid/TP40004399-CH1-SW1

在开发中遇到了上面的错误描述,描述中还有一些数据库表的信息,这种错误是由于覆盖安装App时,本次使用的coredata结构和之前版本的coredata结构不同导致的。

如果想快速跑通程序,可以将之前的App删掉重新安装新App,但是这并非根本解决方法,假设我们的App是已经上线的,当我们推出新版本时需要用户从App Store进行更新,用户并不会先把老版本删除再安装新的,这样变会出现App刚启动就崩溃或者之前数据库中的数据丢失的问题。

根本解决该问题的办法是进行coredata数据迁移,保持前一个版本的coredata结构不变,生成新的结构。以下是迁移过程的截图。


首先选中coredata文件


然后选择Editor->Add Model Version...

iOS CoreData数据迁移_第1张图片


会出现下面的情况

iOS CoreData数据迁移_第2张图片


Finish之后便生成了新的coredata文件

iOS CoreData数据迁移_第3张图片


于是我们将coredata文件切换到新生成的



现在就可以在新的coredata文件中进行数据结构的修改了,除此之外还需要一点代码上的工作。

[objc]  view plain  copy
  1. NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:self.persistentFileName];  
  2.       
  3. NSError *error = nil;  
  4.       
  5. NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption,[NSNumber numberWithBool:YES],NSInferMappingModelAutomaticallyOption, nil nil];  
  6.       
  7. _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];  
  8.       
  9. [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error];  

至此coredata数据迁移完成

你可能感兴趣的:(iOS CoreData数据迁移)