自定义迁移会破坏db

时间:2017-10-12 21:53:10

标签: ios objective-c iphone core-data core-data-migration

当我尝试将旧数据库迁移到新数据库时,这一切都正确完成。但是当我尝试访问数据库时,它说它已损坏或格式错误。它只发生在iOS11中。

我收到此错误 -

error: exception handling request: <NSSQLRelationshipFaultRequestContext: 0x1c4cbc9e0> , Fatal error.  The database at /var/mobile/Containers/Data/Application/743F0953-2F57-4B9F-931A-0E0AEF9E8D0A/Documents/Main.db is corrupted.  SQLite error code:11, 'database disk image is malformed' with userInfo of {
    NSFilePath = "/var/mobile/Containers/Data/Application/743F0953-2F57-4B9F-931A-0E0AEF9E8D0A/Documents/Main.db";
    NSSQLiteErrorDomain = 11;
}

当我尝试访问db时,我得到了 -

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Object's persistent store is not reachable from this NSManagedObjectContext's coordinator'

这是我的迁移代码 -

NSError     *error = nil;
    NSMappingModel                  *mapping = [NSMappingModel inferredMappingModelForSourceModel: oldModel destinationModel: self error: &error];
    if (error) {
        LOG(@"Error while inferring mapping model: %@", error);
        return NO;
    }
    NSString                        *newContextPath = [contextPath stringByAppendingPathExtension: @"tmp"];
    NSValue                         *classValue = [[NSPersistentStoreCoordinator registeredStoreTypes] objectForKey: NSSQLiteStoreType];
    Class                           sqliteStoreClass = (Class)[classValue pointerValue];
    Class                           sqliteStoreMigrationManagerClass = [sqliteStoreClass migrationManagerClass];
    NSURL                           *srcURL = [NSURL fileURLWithPath: contextPath], *dstURL = [NSURL fileURLWithPath: newContextPath];
    NSMigrationManager              *manager = [[sqliteStoreMigrationManagerClass alloc] initWithSourceModel: oldModel destinationModel: self];

    @try {
        if (![manager migrateStoreFromURL: srcURL type:NSSQLiteStoreType options:nil withMappingModel:mapping toDestinationURL: dstURL destinationType:NSSQLiteStoreType destinationOptions:nil error:&error]) {
            LOG(@"Migration failed %@", error);
            return NO;
        }
    } @catch (NSException *exception) {
        LOG(@"Exception: %@", exception);
        return NO;
    }
    if (![[NSFileManager defaultManager] removeItemAtPath: contextPath error: &error]) {
        LOG(@"Error removing old database: %@", error);
        return NO;
    }

    if (![[NSFileManager defaultManager] moveItemAtPath: newContextPath toPath: contextPath error: &error]) {
        LOG(@"Error renaming/moving new database: %@", error);
        return NO;
    }
        LOG(@"- Context Migration: Complete");

1 个答案:

答案 0 :(得分:0)

我终于发现,我只删除了.db文件,但没有删除.shm和.wal文件。这对于iOS10及以下版本是可以的,但不知何故会破坏iOS11中的数据库。因此,删除旧的.shm和.wal文件修复了该问题。

如果有人在遇到问题,那可能会有所帮助。