app中使用了CoreData,并且在下一个版本中有实体变动,比如实体新增字段、修改字段等改动,
那么app在覆盖安装时就要进行数据库迁移,
否则app就会crash。
那如何实现数据库迁移呢?大概需要这几个步骤:
1. 选中你的CoreData.xcdatamodeld文件,选择Xcode菜单editor->Add Model Version
比如取名:mydata2.xcdatamodel


2. 起一个名字,也就是当前新版本CoreData文件的名字。然后点击确认。

3. 这时候会发现CoreData.xcdatamodeld中多了一个版本文件。如图:

4.选择刚才创建的版本,在inspector中的Versioned Core Data Model选择Current模版为CoreData2

5. 修改新数据模型CoreData2,在新的文件上添加属性和修改实体。
6. 删除原来的实体文件,重新生成下的类。

7. 在persistentStoreCoordinator中添加代码:

8. 重新编译运行就OK了。
PS: Xcode8 系统CoreData类做了不少改动,当然使用起来更简单了,如果您是用Xcode8创建的工程实现版本升级和数据迁移,则直接修改实体,然后重新生成即可,非常简单。具体使用和代码见https://github.com/qindeli/XCode8-CoreData-/tree/master/TestCoreData.
网友评论
.m文件
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
#pragma mark - Core Data stack
@synthesize persistentContainer = _persistentContainer;
- (NSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentContainer alloc] initWithName:@"MessageModel"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}];
}
}
return _persistentContainer;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *context = self.persistentContainer.viewContext;
NSError *error = nil;
if ([context hasChanges] && ![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong) NSPersistentContainer *persistentContainer;
- (void)saveContext;
@EnD