文档中的示例(https://realm.io/docs/swift/latest/#compacting-realms)对我来说不是很清楚,因为我不知道是否可以在应用程序使用期间始终调用压缩,或者在启动时只调用一次压缩。下面的实现是否正确,或者做一个单独的配置,包括shouldCompactOnLaunch在应用启动时调用一次会更好。如何在RealmSwift中正确使用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
}
还有一件事对我很有趣:如果压实失败会发生什么?太少的存储将是一个原因。我仍然可以访问数据,压缩只会被忽略吗?