用于打开商店的模型与用于创建商店的模型不兼容

dej*_*ong 180 iphone core-data ios

我在xcode 3.2中创建了一个Core Data模型,在Xcode 4.2中升级后,我添加了NSManagedObject子类的新实体(请参阅新实体).

首先,它看起来很奇怪,因为它与旧的不在同一组中.这是我的xcode 4.2上的图片(AlkitabDB是我在xcode 3.2中创建的,EndeDB是当前xcode版本中的新版本(4.2):

新实体未分组在xdatamodel中

第二件事,我让它原样,然后我以与第一个实体(旧实体)相同的方式访问第二个实体(新实体),并出现标题错误.

这是错误:

2012-01-16 21:13:38.496 iHuria[55953:207] Unresolved error Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x8829cd0 {metadata=<CFBasicHash 0x882a370 [0x1839b38]>{type = immutable dict, count = 7,
entries =>
    2 : <CFString 0x8829b90 [0x1839b38]>{contents = "NSStoreModelVersionIdentifiers"} = <CFArray 0x8829ff0 [0x1839b38]>{type = immutable, count = 0, values = ()}
    4 : <CFString 0x8829bc0 [0x1839b38]>{contents = "NSPersistenceFrameworkVersion"} = <CFNumber 0x8829770 [0x1839b38]>{value = +320, type = kCFNumberSInt64Type}
    6 : <CFString 0x8829bf0 [0x1839b38]>{contents = "NSStoreModelVersionHashes"} = <CFBasicHash 0x882a080 [0x1839b38]>{type = immutable dict, count = 1,
entries =>
    0 : <CFString 0x882a010 [0x1839b38]>{contents = "AlkitabDB"} = <CFData 0x882a030 [0x1839b38]>{length = 32, capacity = 32, bytes = 0xd02ac5f8be6ab0b39add450aca202ac0 ... 3d45d462998d2ccd}
}

    7 : <CFString 0x10e3aa8 [0x1839b38]>{contents = "NSStoreUUID"} = <CFString 0x8829e60 [0x1839b38]>{contents = "4F2EE7FF-463B-4055-BBED-8E603CDBDF59"}
    8 : <CFString 0x10e3948 [0x1839b38]>{contents = "NSStoreType"} = <CFString 0x10e3958 [0x1839b38]>{contents = "SQLite"}
    9 : <CFString 0x8829c40 [0x1839b38]>{contents = "NSStoreModelVersionHashesVersion"} = <CFNumber 0x6b1c7c0 [0x1839b38]>{value = +3, type = kCFNumberSInt32Type}
    10 : <CFString 0x8829c70 [0x1839b38]>{contents = "_NSAutoVacuumLevel"} = <CFString 0x882a0c0 [0x1839b38]>{contents = "2"}
}
, reason=The model used to open the store is incompatible with the one used to create the store}, {
    metadata =     {
        NSPersistenceFrameworkVersion = 320;
        NSStoreModelVersionHashes =         {
            AlkitabDB = <d02ac5f8 be6ab0b3 9add450a ca202ac0 ebd1e860 cbb578c2 3d45d462 998d2ccd>;
        };
        NSStoreModelVersionHashesVersion = 3;
        NSStoreModelVersionIdentifiers =         (
        );
        NSStoreType = SQLite;
        NSStoreUUID = "4F2EE7FF-463B-4055-BBED-8E603CDBDF59";
        "_NSAutoVacuumLevel" = 2;
    };
    reason = "The model used to open the store is incompatible with the one used to create the store";
}
Run Code Online (Sandbox Code Playgroud)

之前我找了解决方案,发现我应该从模拟器中删除应用程序并重新运行应用程序,但它不起作用.有谁知道这个问题的解决方案?请帮忙.

Sta*_*tas 287

删除应用有时并非如此!建议,您的应用已经发布!您不能只是将新实体添加到数据库并继续 - 您需要执行迁移!

对于那些不想深入了解文档并正在寻找快速修复的人:

  1. 打开.xcdatamodeld文件
  2. 单击编辑器
  3. 选择添加型号版本...
  4. 添加模型的新版本(添加了新的数据模型组)
  5. 选择主文件,打开文件检查器(右侧面板)
  6. Versioned core data model为当前数据模型选择新版本的数据模型
  7. 这不是全部)你应该执行所谓的"轻度迁移".
  8. 转到您的位置AppDelegate,找到persistentStoreCoordinator正在创建的位置
  9. 找到这一行 if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
  10. 替换nil选项@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}(实际在该方法的注释代码中提供)
  11. 在这里,你玩得开心!

PS这仅适用于轻量级迁移.要使您的迁移符合轻量级迁移的要求,您的更改必须限制在此窄带:

  • 添加或删除属性(属性或关系).
  • 使非可选属性可选.
  • 只要提供默认值,就可以选择非可选属性.
  • 添加或删除实体.
  • 重命名一个属性.
  • 重命名实体.

对于Swift 4

coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true])
Run Code Online (Sandbox Code Playgroud)

  • Swift Migration选项:`let options = [NSMigratePersistentStoresAutomaticallyOption:true,NSInferMappingModelAutomaticallyOption:true] (3认同)
  • 主文件是您创建的.xcdatamodel.您应该打开Utilities窗格的第一个选项卡(右侧一个)并找到"Model Version"(Xcode 5.1)并选择Current:"您新创建的.xcdatamodel" (2认同)
  • 我收到此错误:"CoreData:error:-addPersistentStoreWithType:SQLite configuration:(null)URL:file:///...file.sqlite options:{NSInferMappingModelAutomaticallyOption = 1; NSMigratePersistentStoresAutomaticallyOption = 1;} ...返回错误错误Domain = NSCocoaErrorDomain Code = 134130"操作无法完成.(可可错误134130.)" (2认同)

Phi*_*rin 284

从模拟器中删除应用程序并对项目执行清理.这应该清除这些问题.删除应用程序时确保没有在调试器中运行,否则它实际上不会正确删除它.

如果您想确定它已消失,请Users/INSERT_YOUR_USER_HERE/Library/Application Support/iPhone Simulator/在您正在运行的版本下检查此应用程序文件夹的目录.

注意:这仅用于开发.对于生产,您需要实现某种迁移.谷歌"核心数据迁移",轻量级迁移是最简单的.

  • 这只是为了开发!对于生产,您使用模型版本控制和迁移.http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/CoreDataVersioning/Articles/Introduction.html (6认同)

Dha*_*ena 34

只需在AppDelegate.m文件中为核心数据方法创建persistentStoreCoordinator时添加Options属性,如下所示

Objective-C的

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil)
    {
        return _persistentStoreCoordinator;
    }

    NSLog(@"persistentStoreCoordinator___");
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MyApp.sqlite"];

    NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
    [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
    [options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    NSLog(@"persistentStoreCoordinator___2");
    return _persistentStoreCoordinator;
}
Run Code Online (Sandbox Code Playgroud)

迅速

    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."

    // MAIN LINE OF CODE TO ADD
    let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true,
                    NSInferMappingModelAutomaticallyOption: true]

    do {
        try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions)
    } catch {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason

        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // Replace this 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 \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }

    return coordinator
}
Run Code Online (Sandbox Code Playgroud)

它解决了我的问题..


Bha*_*vin 23

答案:从模拟器中删除应用程序,执行清理并重新构建项目.

注意:每当您对Core Data定义执行更改时,请删除物理设备或模拟器上安装的应用程序,再次清理项目并重新构建.


小智 14

是.一旦删除物理设备上的应用程序并重建它就可以了.

  • 这是一个可怕的答案,您需要将迁移添加到新模型,否则应用程序将在产品中崩溃 (2认同)

小智 14

对于swift,在AppDelegate.swift中找到该行

try coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration:  nil, URL: url, options: nil )
Run Code Online (Sandbox Code Playgroud)

并替换它

try coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true])
Run Code Online (Sandbox Code Playgroud)


Sym*_*ric 11

我只花了几天时间来对抗这个错误,以及mergedModelFromBundles崩溃,并获得"无法合并模型与两个不同的名为*的实体"错误.

事实证明,根本问题是Xcode不会从设备中删除旧资源,而且我的旧版本的数据模型(.mom文件)导致了冲突.这就是为什么删除应用程序修复了我的一个设备上的问题.

通过另一个SO回答找到这个博客文章后,我通过更改查找所有.mom文件的行来使我的应用程序更容忍旧模型:

NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
Run Code Online (Sandbox Code Playgroud)

对此,它只查看Filters目录:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Filters" ofType:@"momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
Run Code Online (Sandbox Code Playgroud)

我从这个问题中使用了recursivePathsForResourcesOfType:通过记录应用程序中的所有.mom文件来帮助解决这个问题:

NSArray *momPaths = [self recursivePathsForResourcesOfType:@"mom" inDirectory:[[NSBundle mainBundle] resourcePath]];
NSLog(@"All .mom files:%@",momPaths);
Run Code Online (Sandbox Code Playgroud)

我还使用iExplorer来查看无关的.mom文件(我还没有尝试删除它们).

以下方法也很有帮助.它表明一个实体在[psc managedObjectModel]返回的合并模型中,在我的任何模型或商店本身中都不再存在.这让我相信一个旧模型被缓存在设备本身上,清洁建筑没有移除.该方法记录每个与模型相同,已更改,或添加到模型或从模型中删除的实体.(用这个SO答案作为起点):

- (BOOL)comparePersistentStore:(NSPersistentStoreCoordinator *)psc withStoreURL: (NSURL *)storeURL {
    NSError *error = nil;

    // Get the entities & keys from the persistent store coordinator
    NSManagedObjectModel *pscModel = [psc managedObjectModel];
    NSDictionary *pscEntities = [pscModel entitiesByName];
    NSSet *pscKeys = [NSSet setWithArray:[pscEntities allKeys]];
    //NSLog(@"psc model:%@", pscModel);
    //NSLog(@"psc keys:%@", pscKeys);
    NSLog(@"psc contains %d entities", [pscModel.entities count]);

    // Get the entity hashes from the storeURL
    NSDictionary *storeMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType
                                                                                          URL:storeURL
                                                                                        error:&error];
    NSDictionary *storeHashes = [storeMetadata objectForKey:@"NSStoreModelVersionHashes"];
    //NSLog(@"store metadata:%@", sourceMetadata);
    NSLog(@"store URL:%@", storeURL);
    NSLog(@"store NSStoreUUID:%@", [storeMetadata objectForKey:@"NSStoreUUID"]);
    NSLog(@"store NSStoreType:%@", [storeMetadata objectForKey:@"NSStoreType"]);
    NSSet *storeKeys = [NSSet setWithArray:[storeHashes allKeys]];

    // Determine store entities that were added, removed, and in common (to/with psc)
    NSMutableSet *addedEntities = [NSMutableSet setWithSet:pscKeys];
    NSMutableSet *removedEntities = [NSMutableSet setWithSet:storeKeys];
    NSMutableSet *commonEntities = [NSMutableSet setWithSet:pscKeys];
    NSMutableSet *changedEntities = [NSMutableSet new];
    [addedEntities minusSet:storeKeys];
    [removedEntities minusSet:pscKeys];
    [commonEntities minusSet:removedEntities];
    [commonEntities minusSet:addedEntities];

    // Determine entities that have changed (with different hashes)
    [commonEntities enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
        NSData *storeHash = [storeHashes objectForKey:key];
        NSEntityDescription *pscDescrip = [pscEntities objectForKey:key];
        if ( ! [pscDescrip.versionHash isEqualToData:storeHash]) {
            if (storeHash != nil && pscDescrip.versionHash != nil) {
                [changedEntities addObject:key];
            }
        }
    }];

    // Remove changed entities from common list
    [commonEntities minusSet:changedEntities];

    if ([commonEntities count] > 0) {
        NSLog(@"Common entities:");
        [commonEntities enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
            NSData *storeHash = [storeHashes objectForKey:key];
            NSEntityDescription *pscDescrip = [pscEntities objectForKey:key];
            NSLog(@"\t%@:\t%@", key, pscDescrip.versionHash);
        }];
    }
    if ([changedEntities count] > 0) {
        NSLog(@"Changed entities:");
        [changedEntities enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
            NSData *storeHash = [storeHashes objectForKey:key];
            NSEntityDescription *pscDescrip = [pscEntities objectForKey:key];
            NSLog(@"\tpsc   %@:\t%@", key, pscDescrip.versionHash);
            NSLog(@"\tstore %@:\t%@", key, storeHash);
    }];
    }
    if ([addedEntities count] > 0) {
        NSLog(@"Added entities to psc model (not in store):");
        [addedEntities enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
            NSEntityDescription *pscDescrip = [pscEntities objectForKey:key];
            NSLog(@"\t%@:\t%@", key, pscDescrip.versionHash);
        }];
    }
    if ([removedEntities count] > 0) {
        NSLog(@"Removed entities from psc model (exist in store):");
        [removedEntities enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
            NSData *storeHash = [storeHashes objectForKey:key];
            NSLog(@"\t%@:\t%@", key, storeHash);
        }];
    }

    BOOL pscCompatibile = [pscModel isConfiguration:nil     compatibleWithStoreMetadata:storeMetadata];
    NSLog(@"Migration needed? %@", pscCompatibile?@"no":@"yes");

    return pscCompatibile;
}
Run Code Online (Sandbox Code Playgroud)

用法:在将每个商店添加到NSPersistentStoreCoordinator之前调用:

    [self comparePersistentStore:self.psc withStoreURL:self.iCloudStoreURL];
    _iCloudStore = [self.psc addPersistentStoreWithType:NSSQLiteStoreType
                                          configuration:nil
                                                    URL:self.iCloudStoreURL
                                                options:options
                                                  error:&localError];
Run Code Online (Sandbox Code Playgroud)


pie*_*fou 10

每次更改Core Date定义时,都应删除物理设备或模拟器上安装的应用程序.

  • 生产应用程序怎么样?如果您通过更改Core Data将更新推送到App Store,它们会立即崩溃吗?谢谢 (20认同)
  • 是的,CD模型中的更改会阻止加载先前模型生成的数据.要处理此问题,您需要检测问题并执行核心数据迁移. (3认同)

Tom*_*ard 9

  1. 阻止应用程序运行.
  2. 在模拟器上删除应用程序.
  3. Product - > Clean
  4. 构建,运行.

  • 生产中的不良做法,使应用程序崩溃 (3认同)

Nai*_*hta 7

在Swift 2.1中,Xcode 7最简单的解决方案是:

  1. 从模拟器中删除应用程序(Cmd + Shift + H进入主屏幕.长按应用程序,单击交叉,只需按照通常的方式从手机中删除应用程序)

  2. Cmd + Shift + H再次停止应用程序的跳舞

  3. 回到你的项目并重新运行

我在创建2个实体时从Core Data写入/读取时遇到了这个问题.删除应用程序并重新运行该程序修复了该问题

  • 生产中的不良做法,导致应用崩溃 (2认同)

AHH*_*HHP 6

我刚刚[Simulator App Folder]/Document/*.sqlite在实体中进行了更改后删除了文件并且工作正常.当然,.sqlite文件包含将丢失的所有存储数据和结构.

  • 也为我工作过.这应该足够了似乎是合理的.你丢失了数据库中已有的所有数据... (2认同)

小智 6

请从模拟器中删除一个应用程序并清理代码然后运行.工作正常.它可能对你有所帮助.


JZ.*_*JZ. 6

如果您使用的是Swift.

按照@Stas的回答,在App Delegate中插入选项代替nil:

let myOptions = [NSMigratePersistentStoresAutomaticallyOption: true,
            NSInferMappingModelAutomaticallyOption: true]
        if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: myOptions, error: &error) == nil {
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试在模拟器中"重置内容和设置".删除app和Clean build后为我工作

  • 但是,如果执行此操作,真实计算机上的用户是否仍会出现同样的问题? (3认同)