John B. John B. - 6 months ago 18
iOS Question

Realm: How to get the current size of the database

Is there a Realm API method to get the current database size of my RealmSwift app using RealmSwift as data storage? So that I could display that information in the app itself (like statistic information).

Thanks in advance

John

Answer

Realm's APIs doesn't offer such a method. But for these purposes, it seems to be sufficient to use Foundation's NSFileManager API.

let realm = …
let path = realm.configuration.fileURL!.path
let attributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(realm.path)
let fileSize = attributes.fileSize()

Note though: the reported file size is not completely occupied by data. For performance reasons, Realm is acquiring more disk space beforehand. If you want the disk usage of the actual stored data, you would need to write a compacted copy first and could measure that, but this seems to be for the use-case of reporting it to an end-user rather misleading and would hit the performance.

Update:

Realm is using NSURL for paths since version 0.99+. The sample code was changed accordingly.