核心数据NSPersistentStoreCoordinator&+ 39; metadataForPersistentStoreOfType:URL:错误:有时返回nil

时间:2014-04-02 16:48:22

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

我有一种方法可以逐步迁移core data sqlite商店,但是存储多个NSManagedObjectModel版本,直到商店处于当前版本。该方法的灵感来自Marcus Zarra的核心数据手册中的代码。

该应用程序已投入生产,但我的方法在约0.5%的情况下失败。当它失败时返回NO并使用Crashlytics记录错误:

NSSQLiteErrorDomain = 14; NSUnderlyingException = "I/O error for database at <store url>. SQLite error code:14, 'unable to open database file'"

sqlite商店使用预写日志记录(WAL)如果我在首次手动删除{+metadataForPersistentStoreOfType:URL:error:后调用sqlite-WAL,我有时会遇到同样的错误{1}}档案。

渐进式迁移代码:

- (BOOL)progressivelyMigrateURL:(NSURL*)sourceStoreURL 
                        toModel:(NSManagedObjectModel*)finalModel 
                          error:(NSError**)error
{
    NSURL *storeDirectoryURL = [sourceStoreURL URLByDeletingLastPathComponent];
    NSString *storeExtension = [sourceStoreURL pathExtension];

    NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator 
        metadataForPersistentStoreOfType:NSSQLiteStoreType 
                                     URL:sourceStoreURL 
                                   error:error];
    if (!sourceMetadata) return NO;

    while (![finalModel isConfiguration:nil 
            compatibleWithStoreMetadata:sourceMetadata]) {

        NSManagedObjectModel *sourceModel = 
            [self managedObjectModelForMetadata:sourceMetadata];
        if (!sourceModel) return NO;

        NSString *modelName = nil;
        NSManagedObjectModel *targetModel = 
            [self suitableTargetModelForMigrationFromSourceModel:sourceModel 
                                                       modelName:&modelName];
        if (!targetModel) return NO;

        NSMigrationManager *manager = 
            [[NSMigrationManager alloc] initWithSourceModel:sourceModel 
                                           destinationModel:targetModel];
        NSMappingModel *mappingModel = 
            [NSMappingModel mappingModelFromBundles:nil 
                                     forSourceModel:sourceModel 
                                   destinationModel:targetModel];
        NSURL *destinationStoreURL = 
            [[storeDirectoryURL URLByAppendingPathComponent:modelName] 
                URLByAppendingPathExtension:storeExtension];

        BOOL migrated = [manager migrateStoreFromURL:sourceStoreURL 
                                                type:NSSQLiteStoreType 
                                             options:nil 
                                    withMappingModel:mappingModel 
                                    toDestinationURL:destinationStoreURL 
                                     destinationType:NSSQLiteStoreType 
                                  destinationOptions:nil 
                                               error:error];
        if (!migrated) return NO;

        NSString *sourceModelName = 
            [self versionStringForManagedObjectModel:sourceModel];
        NSURL *backUpURL = [self backupURLWithDirectoryURL:storeDirectoryURL 
                                             pathExtension:storeExtension 
                                                 modelName:sourceModelName];
        BOOL replaced = [self replaceStoreAtURL:sourceStoreURL 
                                 withStoreAtURL:destinationStoreURL 
                                      backupURL:backUpURL 
                                          error:error];
        if (replaced == NO) return NO;

        sourceMetadata = [NSPersistentStoreCoordinator 
            metadataForPersistentStoreOfType:NSSQLiteStoreType 
                                         URL:sourceStoreURL 
                                       error:error];
        if (!sourceMetadata) return NO;
    }

    return YES;
}

- (NSManagedObjectModel *)managedObjectModelForMetadata:(NSDictionary *)metadata
{
    for (NSURL *URL in [self modelURLs]) {
        NSManagedObjectModel *model = 
            [[NSManagedObjectModel alloc] initWithContentsOfURL:URL];
        if ([model isConfiguration:nil compatibleWithStoreMetadata:metadata]) {
            return model;
        }
    }
    return nil;
}

- (NSManagedObjectModel *)suitableTargetModelForMigrationFromSourceModel:(NSManagedObjectModel *)sourceModel 
                                                               modelName:(NSString **)modelName
{
    for (NSURL *modelURL in [self modelURLs]) {
        NSManagedObjectModel *targetModel = 
            [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
        NSMappingModel *mappingModel = 
            [NSMappingModel mappingModelFromBundles:nil 
                                     forSourceModel:sourceModel 
                                   destinationModel:targetModel];

        if (mappingModel) {
            *modelName = [[modelURL lastPathComponent] stringByDeletingPathExtension];
            return targetModel;
        }
    }

    return nil;
}

- (NSArray *)modelURLs
{
    NSMutableArray *modelURLs = 
        [[[NSBundle mainBundle] URLsForResourcesWithExtension:@"mom" 
                                                 subdirectory:nil] mutableCopy];

    NSArray *momdURLs = 
        [[[NSBundle mainBundle] URLsForResourcesWithExtension:@"momd" 
                                                 subdirectory:nil] mutableCopy];
    for (NSURL *momdURL in momdURLs) {
        NSString *directory = [momdURL lastPathComponent];
        NSArray *array = 
            [[NSBundle mainBundle] URLsForResourcesWithExtension:@"mom" 
                                                    subdirectory:directory];
        [modelURLs addObjectsFromArray:array];
    }

    return [modelURLs copy];
}

- (NSURL *)backupURLWithDirectoryURL:(NSURL *)URL 
                       pathExtension:(NSString *)extension 
                           modelName:(NSString *)name
{
    NSString *GUID = [[NSProcessInfo processInfo] globallyUniqueString];
    NSString *pathComponant = [NSString stringWithFormat:@"%@-%@", GUID, name];

    return [[URL URLByAppendingPathComponent:pathComponant] 
        URLByAppendingPathExtension:extension];
}

- (BOOL)replaceStoreAtURL:(NSURL *)originalStoreURL 
           withStoreAtURL:(NSURL *)newStoreURL 
                backupURL:(NSURL *)backupURL 
                    error:(NSError **)error
{
    BOOL storeMoved = [self moveStoreAtURL:originalStoreURL 
                                     toURL:backupURL 
                                     error:error];
    if (!storeMoved) return NO;

    storeMoved = [self moveStoreAtURL:newStoreURL 
                                toURL:originalStoreURL 
                                error:error];
    if (!storeMoved) return NO;

    return YES;
}

- (BOOL)moveStoreAtURL:(NSURL *)sourceURL 
                 toURL:(NSURL *)targetURL 
                 error:(NSError **)error
{
    NSMutableArray *sourceURLs = [@[sourceURL] mutableCopy];
    NSMutableArray *targetURLs = [@[targetURL] mutableCopy];

    NSString *walExtension = @"sqlite-wal";
    if ([self storeAtURL:sourceURL hasAccessoryFileWithExtension:walExtension]) {
        [sourceURLs addObject:[self URLByReplacingExtensionOfURL:sourceURL 
                                                   withExtension:walExtension]];
        [targetURLs addObject:[self URLByReplacingExtensionOfURL:targetURL 
                                                   withExtension:walExtension]];
    }

    NSString *shmExtension = @"sqlite-shm";
    if ([self storeAtURL:sourceURL hasAccessoryFileWithExtension:shmExtension]) {
        [sourceURLs addObject:[self URLByReplacingExtensionOfURL:sourceURL 
                                                   withExtension:shmExtension]];
        [targetURLs addObject:[self URLByReplacingExtensionOfURL:targetURL 
                                                   withExtension:shmExtension]];
    }

    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (int i = 0; i < [sourceURLs count]; i++) {
        BOOL fileMoved = [fileManager moveItemAtURL:sourceURLs[i] 
                                              toURL:targetURLs[i] 
                                              error:error];
        if (!fileMoved) return NO;
    }

    return YES;
}

- (BOOL)storeAtURL:(NSURL *)URL hasAccessoryFileWithExtension:(NSString *)extension
{
    NSURL *accessoryURL = [self URLByReplacingExtensionOfURL:URL 
                                               withExtension:extension];
    return [[NSFileManager defaultManager] fileExistsAtPath:[accessoryURL path]];
}

- (NSURL *)URLByReplacingExtensionOfURL:(NSURL *)URL withExtension:(NSString *)extension
{
    return [[URL URLByDeletingPathExtension] URLByAppendingPathExtension:extension];
}

- (NSString *)versionStringForManagedObjectModel:(NSManagedObjectModel *)model
{
    NSString *string = @"";
    for (NSString *identifier in model.versionIdentifiers) {
        string = [string stringByAppendingString:identifier];
    }
    return string;
}

抱歉超长代码。

2 个答案:

答案 0 :(得分:3)

可能的原因是您的moveStoreAtURL:toURL:error:方法。您获得的错误是mentioned in Apple's docs,因为无法复制所有持久性存储的文件。看起来你正试图点击所有这些,但是(a)复制代码中有一个我现在无法找到的错误或(b)商店在你的应用程序中“活着”,正在使用持久存储协调器,因此您无法从副本获得一致的状态。

您可以通过一些调试来修复它,如果您确保该商店未被使用。更改日志模式会更好,也可能更可靠,因此您没有walshm文件(该链接也描述了这些文件)。更好的是,如果您的商店文件不是太大,请使用migratePersistentStore:toURL:options:withType:error让Core Data制作副本。这应该可以保证工作,但在某些情况下它可能会占用太多内存。

答案 1 :(得分:2)

我使用NSMigrationManager,因此我无法使用NSPersistentStoreCoordinator&#39; s - migratePersistentStore...,所以我的解决方案是强制执行检查点操作:

- (void)performCheckpointStoreWithSourceModel:(NSManagedObjectModel *)sourceModel sourceStoreURL:(NSURL *)sourceStoreURL {
    NSPersistentStoreCoordinator *tempPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:sourceModel];
    [tempPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sourceStoreURL options:@{NSSQLitePragmasOption: @{@"journal_mode": @"DELETE"}} error:nil];
    [tempPSC removePersistentStore:[tempPSC persistentStoreForURL:sourceStoreURL] error:nil];
}

...在使用NSMigrationManager执行迁移之前:

if (![manager migrateStoreFromURL:sourceStoreURL
                             type:type
                          options:nil
                 withMappingModel:mappingModel
                 toDestinationURL:destinationStoreURL
                  destinationType:type
               destinationOptions:nil
                            error:error]) {
    return NO;
}