如何在RealmSwift中正确使用shouldCompactOnLaunch [英] How to correctly use shouldCompactOnLaunch in RealmSwift

查看:238
本文介绍了如何在RealmSwift中正确使用shouldCompactOnLaunch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档中的示例( https://realm.io/docs/swift/latest/#compacting-realms )对我来说不是很清楚,因为我不知道是否可以在应用程序使用过程中始终调用压缩,还是在启动时仅调用一次.下面的实现是正确的还是最好做一个单独的配置,包括shouldCompactOnLaunch,以便在应用启动时调用一次.

The example in the documentation (https://realm.io/docs/swift/latest/#compacting-realms) is not very clear to me, as I don't know if the compaction could be called all the time during app use or only once at startup. Is the implementation below correct or would it be better to make a separate config including shouldCompactOnLaunch to call once on app launch.

如果将shouldCompactOnLaunch添加到默认配置,则每次创建领域实例时都会看到该块被调用.

If I add shouldCompactOnLaunch to the default configuration I see the block being called every time I create a realm instance.

        Realm.Configuration.defaultConfiguration = Realm.Configuration(schemaVersion: schemaVersion, migrationBlock: migrationBlock,shouldCompactOnLaunch: { totalBytes, usedBytes in
        // totalBytes refers to the size of the file on disk in bytes (data + free space)
        // usedBytes refers to the number of bytes used by data in the file

        // Compact if the file is over 100MB in size and less than 50% 'used'
        let oneHundredMB = 100 * 1024 * 1024
        print ("totalbytes \(totalBytes)")
        print ("usedbytes \(usedBytes)")
        if (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.7{
            print("will compact realm")
        }
        return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.7
    })
    do {
        // Realm is compacted on the first open if the configuration block conditions were met.
        _ = try Realm(configuration: config)
    } catch {
        // handle error compacting or opening Realm
    }

还有一件令我感兴趣的事情:如果压缩失败,会发生什么?太少的存储空间将是一个原因.我是否仍然可以访问数据并且压缩将被跳过?

And one more thing would be interesting to me: What happens if the compaction fails? Too little storage would be a reason. Will I still be able to access the data and the compaction will just be skipped?

推荐答案

所以对我来说,解决方案是创建配置.除 shouldCompactOnLaunch 块中的配置外,配置与相同.这个配置了shouldCompactOnLaunch的配置,我只是在应用启动时使用一次,所以它不会每次都被触发.

So the solution for me was to create to configs. The configs are identical except of the shouldCompactOnLaunch block. This config with the shouldCompactOnLaunch I just use once at app launch, so it does not get triggered every time.

这是 Realm github问题

如果执行失败,则该应用将继续使用数据库的未压缩版本.

If the compaction fails the app will continue using the uncompacted version of the database.

这篇关于如何在RealmSwift中正确使用shouldCompactOnLaunch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆