文檔中的示例(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
}
還有一件事對我很有趣:如果壓實失敗會發生什麼?太少的存儲將是一個原因。我仍然可以訪問數據,壓縮只會被忽略嗎?