`

coredata 轻量级 迁移(4.2以上)

 
阅读更多

当CoreData中的Entity,Property或者Relationship发生改变以后,默认情况下面,在尝试调用CoreData的时候,程序会异常退出。

 

 

怎样开启自动迁移的功能?分三步

1.在App delegate类里修改persistentStoreCoordinator方法

 

 

  1. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {  
  2.     if (__persistentStoreCoordinator != nil) {  
  3.         return __persistentStoreCoordinator;  
  4.     }  
  5.       
  6.     NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"WorkXP.sqlite"];  
  7.       
  8.     NSError *error = nil;  
  9.     __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];  
  10.       
  11.     // handle db upgrade  
  12.     NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:  
  13.                              [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,  
  14.                              [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];  
  15.       
  16.     if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {  
  17.        // Handle error  
  18.     }      
  19.       
  20.     return __persistentStoreCoordinator;  
  21. }  

 

 

2. 创建新版本并选择当前active模型版本,

xcode 4里,创建新模型是在Editor里的Add Model Verison,

 

要选择当前使用的数据模型版本,在文件导航中,先选中appname.xcdatamodeld这个,然后在右侧属性栏中Versiond Core Data Model中选择Current的模型版本。

 

3.OK了,再次运行,App可以访问新版本的coredata数据库模型了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics