问题
I'm trying to integrate Realm into my project and noticed an issue. I've seen other posts on this, but they were a little over a year ago and have been resolved..
When adding objects to Realm, things are file. But when removing objects, they get removed from the DB, but the file size is still large. If I open the realm file in TextEdit, I can see raw text of old records. Why aren't they getting fully deleted?
Take a look at this screenshot. Zero files in the Realm DB, but the file size is 23 mb.
Thanks.
回答1:
as bcamur sad,
the Realm file will maintain its size on disk to efficiently reuse that space for future objects
but there is also written
The extra space will eventually be reused by future writes, or may be compacted — for example by calling
Realm().writeCopyToPath(_:encryptionKey:)
.
and
call
invalidate
to tell Realm that you no longer need any of the objects that you’ve read from the Realm so far, which frees us from tracking intermediate versions of those objects. The Realm will update to the latest version the next time it is accessed
回答2:
Realm holds on to that space to use later on for new objects:
You can also delete all objects stored in a Realm. Note the Realm file will maintain its size on disk to efficiently reuse that space for future objects.
See this part of documentation
回答3:
Swift Version 3.0.1
For compact your DB:
func compactRealm() {
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
let defaultParentURL = defaultURL.deletingLastPathComponent()
let compactedURL = defaultParentURL.appendingPathComponent("default-compact.realm")
autoreleasepool {
let realm = try! Realm()
try! realm.writeCopy(toFile: compactedURL)
try! FileManager.default.removeItem(at: defaultURL)
try! FileManager.default.moveItem(at: compactedURL, to: defaultURL)
}
}
来源:https://stackoverflow.com/questions/35865711/realm-file-size-is-too-large