【问题标题】:iOS: How can I create a backup copy of my core data base? And how to export/import that copy?iOS:如何创建核心数据库的备份副本?以及如何导出/导入该副本?
【发布时间】:2019-07-03 15:09:02
【问题描述】:

我想为我的应用程序的用户提供创建核心数据数据库备份的可能性,尤其是在他切换到新设备等情况下。

我该怎么做?特别是如何重新导入该文件?我的意思是,假设他制作了数据库的备份副本,然后更改了大量内容并希望重置为之前保存的备份副本。我该怎么做?

谢谢!

【问题讨论】:

    标签: ios core-data backup


    【解决方案1】:

    看看这个示例应用程序,它包括制作备份、将备份复制到 iCloud 和从 iCloud 复制备份、通过电子邮件发送备份以及从电子邮件导入备份的功能。 http://ossh.com.au/design-and-technology/software-development/sample-library-style-ios-core-data-app-with-icloud-integration/

    顺便说一句,使用 migratePersistentStore API 来制作/导入备份会更安全,如果您在 ICloud 之间这样做的话。另请注意,示例应用程序假定您未使用 WAL 模式,这是 iOS 7 的默认模式。WAL 模式使用多个文件,所有文件都需要备份或复制。

    这里是演示示例应用程序备份和恢复功能的视频的链接。

    http://ossh.com.au/design-and-technology/software-development/sample-library-style-ios-core-data-app-with-icloud-integration/sample-apps-explanations/backup-files/

    以下是用于创建备份副本的方法。请注意,可以使用多个persistentStoreCoordinators 打开存储,因此在进行备份时无需关闭它。恢复它显然需要先删除现有的商店。请注意,以下两种方法几乎没有区别,只是源存储是在有或没有 iCloud 选项的情况下打开的。

        /*! Creates a backup of the ICloud store
    
         @return Returns YES of file was migrated or NO if not.
         */
        - (bool)backupICloudStore {
            FLOG(@"backupICloudStore called");
    
    
            // Lets use the existing PSC
            NSPersistentStoreCoordinator *migrationPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
    
            // Open the store
            id sourceStore = [migrationPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self icloudStoreURL] options:[self icloudStoreOptions] error:nil];
    
            if (!sourceStore) {
    
                FLOG(@" failed to add old store");
                migrationPSC = nil;
                return FALSE;
            } else {
                FLOG(@" Successfully added store to migrate");
    
                NSError *error;
    
                FLOG(@" About to migrate the store...");
                id migrationSuccess = [migrationPSC migratePersistentStore:sourceStore toURL:[self backupStoreURL] options:[self localStoreOptions] withType:NSSQLiteStoreType error:&error];
    
                if (migrationSuccess) {
                    FLOG(@"store successfully backed up");
                    migrationPSC = nil;
                    // Now reset the backup preference
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:_makeBackupPreferenceKey];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    return TRUE;
                }
                else {
                    FLOG(@"Failed to backup store: %@, %@", error, error.userInfo);
                    migrationPSC = nil;
                    return FALSE;
                }
    
            }
            migrationPSC = nil;
            return FALSE;
        }
        /*! Creates a backup of the Local store
    
         @return Returns YES of file was migrated or NO if not.
         */
        - (bool)backupLocalStore {
            FLOG(@"backupLocalStore called");
    
    
            // Lets use the existing PSC
            NSPersistentStoreCoordinator *migrationPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
    
            // Open the store
            id sourceStore = [migrationPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self localStoreURL] options:[self localStoreOptions] error:nil];
    
            if (!sourceStore) {
    
                FLOG(@" failed to add old store");
                migrationPSC = nil;
                return FALSE;
            } else {
                FLOG(@" Successfully added store to migrate");
    
                NSError *error;
    
                FLOG(@" About to migrate the store...");
                id migrationSuccess = [migrationPSC migratePersistentStore:sourceStore toURL:[self backupStoreURL] options:[self localStoreOptions] withType:NSSQLiteStoreType error:&error];
    
                if (migrationSuccess) {
                    FLOG(@"store successfully backed up");
                    migrationPSC = nil;
                    // Now reset the backup preference
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:_makeBackupPreferenceKey];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    return TRUE;
                }
                else {
                    FLOG(@"Failed to backup store: %@, %@", error, error.userInfo);
                    migrationPSC = nil;
                    return FALSE;
                }
    
            }
            migrationPSC = nil;
            return FALSE;
        }
    
    /**  Sets the selected file as the current store.
     Creates a backup of the current store first.
    
     @param fileURL The URL for the file to use.
     */
    - (BOOL)restoreFile:(NSURL *)fileURL {
        FLOG(@" called");
    
        // Check if we are using iCloud
        if (_isCloudEnabled) {
            FLOG(@" using iCloud store so OK to restore");
            NSURL *currentURL = [self storeURL];
            FLOG(@" currentURL is %@", currentURL);
    
            FLOG(@" URL to use is %@", fileURL);
    
            [self saveContext];
    
            [self backupCurrentStoreWithNoCheck];
    
            // Close the current store and delete it
            _persistentStoreCoordinator = nil;
            _managedObjectContext = nil;
    
            [self removeICloudStore];
    
            [self moveStoreFileToICloud:fileURL delete:NO backup:NO];
    
    
        } else {
            FLOG(@" using local store so OK to restore");
            NSURL *currentURL = [self storeURL];
            FLOG(@" currentURL is %@", currentURL);
    
            FLOG(@" URL to use is %@", fileURL);
    
            [self saveContext];
    
            [self backupCurrentStoreWithNoCheck];
    
            // Close the current store and delete it
            _persistentStoreCoordinator = nil;
            _managedObjectContext = nil;
    
            NSError *error = nil;
            NSFileManager *fm = [[NSFileManager alloc] init];
    
            // Delete the current store file
            if ([fm fileExistsAtPath:[currentURL path]]) {
                FLOG(@" target file exists");
                if (![fm removeItemAtURL:currentURL error:&error]) {
                    FLOG(@" error unable to remove current store file");
                    NSLog(@"Error removing item Error: %@, %@", error, error.userInfo);
                    return FALSE;
                } else {
                    FLOG(@" current store file removed");
                }
            }
    
            //
            //simply copy the file over
            BOOL copySuccess = [fm copyItemAtPath:[fileURL path]
                                           toPath:[currentURL path]
                                            error:&error];
            if (copySuccess) {
                FLOG(@" replaced current store file successfully");
                //[self postFileUpdateNotification];
            } else {
                FLOG(@"Error copying items Error: %@, %@", error, error.userInfo);
                return FALSE;
            }
        }
    
        // Now open the store again
    
        [self openPersistentStore];
    
        return TRUE;
    }
    

    【讨论】:

    • 感谢您的回答。持久存储元数据怎么样?我发现在我的 *.sqlite 数据库在其他设备上恢复后我丢失了它。是真的还是我的错?
    • 这段代码很棒。谢谢你。我没有看到将本地存储备份到 iCloud 的选项 - 这可以很容易地完成吗?你会推荐它吗?如何更改代码 - 我知道这比备份到本地目录要复杂得多。我有示例应用程序,所以如果有一种方法我可以在那里添加以将本地存储备份到 iCloud Drive,那就太好了。我想让用户选择上传到 iCloud Drive 或本地目录。
    • @kas-kad 我不确定元数据 - 我从不担心示例代码(或其他任何地方)中的元数据。
    • @SAHM - 自从我查看这段代码以来已经有一段时间了,但据我所知,您可以将数据库备份到本地文件,然后将该文件单独复制到 iCloud 容器。我认为在上述链接的示例应用程序中有执行上述两项操作的代码。
    • @DuncanGroenewald 如果不使用 migratePersistentStore 将文件复制到 iCloud,重要的 WAL 信息不会丢失吗?
    【解决方案2】:

    无论您使用什么持久存储(二进制、SQLite 等);它只是文件系统上的一个文件。您可以随时复制它。

    如果您在 iOS 7 中使用 SQLite,请务必复制与其关联的其他文件,因为它们是随附的日志文件。如果您使用的是二进制文件,那么将只有一个文件。

    如果你只是复制文件没有导入步骤,你只需将它复制回来即可恢复它。

    还有更高级的设计,例如将整个数据库导出为可移植的东西,例如 JSON,但这是一个不同的主题。

    更新

    我使用了标准的 Xcode 核心数据模板,所以根据我刚刚检查的代码,我使用的是 SQLite。那么如何找到所有相关文件呢?或者你能用一些示例代码告诉我如何复制和插入所需的文件吗?

    您使用NSFileManager 来复制文件。您可以查看 iOS 模拟器应用程序中的文档目录以查看所有文件的名称。或者您可以使用NSFileManager 扫描文档目录,找到以相同文件名开头的所有内容(例如MyData.*)并将其复制到备份目录中。

    至于示例代码,没有;查看NSFileManager 的文档后,只需几行代码。

    【讨论】:

    • 嗯,我使用了标准的 Xcode 核心数据模板,所以根据我刚刚检查的代码,我使用的是 SQLite。那么如何找到所有相关文件呢?或者你能告诉我一些示例代码如何复制和插入所需的文件吗?
    • 感谢您的回答。持久存储元数据怎么样?我发现在我的 *.sqlite 数据库在其他设备上恢复后我丢失了它。是真的还是我的错?
    • 如果您只是复制文件,那么您不应该丢失存储在该文件中的元数据。如果您正在执行导出/导入,那么您需要确保也导出元数据。
    • 在 SQL 事务期间以这种方式复制存储可能容易出错。最好使用migratePersistentStoreNSPersistentStoreCoordinator,也可以在之后将其吸尘,然后再将其传递给其他设备。
    • @MarcusS.Zarra 你肯定需要确保你做的有条不紊。这当然需要一定的设计,但在日记模式下,我认为你不能安全地复制 SQLite 存储,因为它的文件很少,你很容易得到不一致或损坏的存储。
    【解决方案3】:

    我在 Apple 示例 code 的帮助下创建了以下方法。这将备份核心数据文件并将其放置到您想要的路径。

    斯威夫特 5

    /// Backing up store type to a new and unique location
    /// The method is illustrated in the following code fragment, which shows how you can use migratePersistentStore to take a back up of a store and save it from one location to another.
    /// If the old store type is XML, the example also converts the store to SQLite.
    /// - Parameters:
    ///   - path: Where you want the backup to be done, please create a new unique directory with timestamp or the guid
    ///   - completion: Passes error in case of error or pass nil in case of success
    class func backUpCoreDataFiles(path : URL, completion : @escaping (_ error : String?) -> ())
    {
    
        // Every time new container is a must as migratePersistentStore method will loose the reference to the container on migration
        let container = NSPersistentContainer(name : "<YourDataModelName>")
        container.loadPersistentStores
            { (storeDescription, error) in
                if let error = error
                {
                    fatalError("Failed to load store: \(error)")
                }
        }
        let coordinator = container.persistentStoreCoordinator
        let store = coordinator.persistentStores[0]
        do
        {
            try coordinator.migratePersistentStore(store, to : path, options : nil, withType : NSSQLiteStoreType)
            completion(nil)
        }
        catch
        {
            completion("\(Errors.coredataBackupError)\(error.localizedDescription)")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      • 2014-08-19
      • 2010-10-22
      • 1970-01-01
      相关资源
      最近更新 更多