【发布时间】:2014-11-15 09:57:59
【问题描述】:
我在 App Store 上有一个使用 Core Data 的应用,我想进行更新。我使用预加载的 sqlite 文件来创建persistentStore。模型中有两个实体,其中一个包含用户保存的数据。
我的问题:我想用新的预加载 sqlite 更新现有的核心数据,但保留用户保存的数据。有没有办法将预加载文件的新数据与用户保存的数据合并?
模型保持不变;我没有添加任何新实体或属性,所以我认为迁移不合适(我可能错了)。
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CreatureData.sqlite"];
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {
NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"CreatureData" ofType:@"sqlite"]];
NSLog(@"JUST LOADED COREDATA SQLITE");
NSError* err = nil;
if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err]) {
NSLog(@"Oops, couldn't copy preloaded data");
}
} else {
NSLog(@"Core Data SQLITE already exists");
}
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
//abort();
}
return _persistentStoreCoordinator;
}
编辑:
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CreatureData.sqlite"];
NSURL *secondStoreURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"CreatureData" ofType:@"sqlite"]];
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {
NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"CreatureData" ofType:@"sqlite"]];
NSLog(@"JUST LOADED COREDATA SQLITE");
NSError* err = nil;
if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err]) {
NSLog(@"Oops, couldn't copy preloaded data");
}
}
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption : @YES,
NSInferMappingModelAutomaticallyOption : @YES };
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:@"UserSavedData" URL:storeURL options:options error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:@"StaticTableData" URL:secondStoreURL options:options error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
【问题讨论】:
标签: sqlite core-data user-input updates