【发布时间】:2017-06-07 08:47:11
【问题描述】:
文档中的示例 (https://realm.io/docs/swift/latest/#compacting-realms) 对我来说不是很清楚,因为我不知道在应用程序使用期间是否可以一直调用压缩,或者在启动时只调用一次。下面的实现是否正确,或者最好制作一个单独的配置,包括 shouldCompactOnLaunch 在应用启动时调用一次。
如果我将 shouldCompactOnLaunch 添加到默认配置中,我会看到每次创建领域实例时都会调用该块。
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
}
还有一件事对我来说很有趣:如果压缩失败会发生什么?存储空间太少是一个原因。我是否仍然可以访问数据并且会跳过压缩?
【问题讨论】: