gpt4 book ai didi

ios - NSPersistentStoreCoordinator在ios中没有持久化存储(Schema不匹配或迁移失败)核心数据iOS

转载 作者:行者123 更新时间:2023-11-29 11:46:51 26 4
gpt4 key购买 nike

我添加了新版本的数据模型。我在新版本中添加了新字段。还将当前模型版本设置为新创建的版本。

代码更新:

 - (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"PPUSFAModel" withExtension:@"momd"];

//I earlier was PPUSFAModel 16, i added new model version PPUSFAModel 17.

_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:SQLITENAME];

NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
//Error
}

return _persistentStoreCoordinator;
}

它一直有效,直到添加了一些属性,但在某些时候我在以下代码处崩溃了

- (void)saveContext
{

__block NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

[managedObjectContext performBlockAndWait:^{

if (managedObjectContext != nil && _persistentStoreCoordinator != nil) {

if ([managedObjectContext hasChanges] && ![managedObjectContext 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.
// DLog(@"Unresolved error %@, %@", error, [error userInfo]);
//abort();
}
} }];
}

这是崩溃的截图:

enter image description here

当我通过从设备上删除较早的应用程序进行安装时,它可以正常工作,但在现有版本上更新应用程序时会崩溃。

//如果我不小心在旧模型版本而不是新版本中添加了字段,该如何解决?

任何帮助将不胜感激。

最佳答案

请确保您已更新模型“当前版本”。 Update "Current Version" in .xcdatamodel -> File Inspector -> Model version

然后转到“AppDelegate.swift”文件并添加以下代码:

let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]

然后将“选项”应用到参数“选项”的以下代码中:

try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)

代码如下所示: image

关于ios - NSPersistentStoreCoordinator在ios中没有持久化存储(Schema不匹配或迁移失败)核心数据iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43279438/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com