gpt4 book ai didi

swift - 如何在 RealmSwift 中正确使用 shouldCompactOnLaunch

转载 作者:搜寻专家 更新时间:2023-10-31 22:27:28 34 4
gpt4 key购买 nike

文档 ( https://realm.io/docs/swift/latest/#compacting-realms ) 中的示例对我来说不是很清楚,因为我不知道压缩是可以在应用程序使用期间一直调用还是仅在启动时调用一次。下面的实现是否正确,或者制作一个单独的配置(包括 shouldCompactOnLaunch 以在应用程序启动时调用一次)会更好吗?

如果我将 shouldCompactOnLaunch 添加到默认配置中,我会在每次创建 Realm 实例时看到该 block 被调用。

        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
}

还有一件事对我来说很有趣:如果压缩失败会发生什么?存储空间太少是一个原因。我是否仍然能够访问数据并且只是跳过压缩?

最佳答案

RLMRealmConfiguration 的头文件中有额外的信息:

/**
A block called when opening a Realm for the first time during the life
of a process to determine if it should be compacted before being returned
to the user. It is passed the total file size (data + free space) and the total
bytes used by data in the file.

Return `YES` to indicate that an attempt to compact the file should be made.
The compaction will be skipped if another process is accessing it.
*/

@property (nonatomic, copy, nullable) RLMShouldCompactOnLaunchBlock shouldCompactOnLaunch;

诚然,我们应该在网站上的文档中更清楚地表明,仅应在第一次创建表示特定 Realm 文件的 Realm 实例时调用此 block 。

如果你确实看到这个 block 被同一个 Realm 文件多次调用,请在 Realm Cocoa GitHub page 上提出一个问题。详细的重现步骤。

一旦您使用特定的Configuration 创建了一个Realm 实例,通常最好的做法是避免事后更改该配置。您不应该创建两个不同的 Configuration 对象,一个带有压缩 block ,一个没有。 Realm 根据其 Configuration 在内部缓存 Realm 实例,因此您可能会遇到不可预测的行为。

压缩不应该失败。唯一会成为问题的主要场景是,如果您的设备已经快要用完硬盘空间了。根据该 Realm 中有多少空闲空间,压缩后的 Realms 通常要小得多,因此整个操作不需要 2 倍的存储大小。在 iOS 上,如果系统检测到其存储空间不足,则会触发“清理”阶段,清除其他应用程序的 Caches 目录,这在绝大多数情况下足以缓解问题完成这个过程。

如果所有这些都失败了,执行压缩的尝试将抛出异常;您的错误处理代码应该能够捕捉到。

关于swift - 如何在 RealmSwift 中正确使用 shouldCompactOnLaunch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44407812/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com