2017-10-12 79 views
0

當我嘗試將我的舊數據庫遷移到新的數據庫時,它都正確完成。但是當我嘗試訪問數據庫時,它說它已損壞或格式不正確。它只發生在iOS11中。自定義遷移損壞db

我得到這個錯誤 -

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; 
} 

,當我嘗試訪問數據庫,我得到 -

*** 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"); 

回答

0

我終於找到了,我只刪除了.db文件,但沒有.shm和.wal文件。這對iOS10及其以下版本可以,但不知何故損壞了iOS11中的數據庫。因此,刪除舊的.shm和.wal文件修復了這個問題。

如果有人正在努力解決問題,這可能會有所幫助。