2016-06-07 87 views
2

我目前正在使用Swift中的iOS項目,並使用Realm作爲我的數據庫。 我存儲了一個Realm對象,它的一個屬性是一個NSData對象(實際上它是一個UIImage,我轉換成了NSData)。我的問題很容易理解:當我存儲一個大小爲3 Mo的NSData對象時,我的Realm文件大小大約是15 Mo。但是當我的NSData對象大小爲6 Mo時,我的Realm文件大小變爲大約80 Mo.存儲不同的NSData時領域文件大小差異

有沒有人遇到過這個問題? 這有什麼不同? 有什麼辦法解決這個問題嗎?

回答

3

領域文件大小不等於存儲數據由於某些原因的大小。

一個是內部版本的數據。

If your Realm file is much larger than you expect, it may be because you have a RLMRealm that is referring to an older version of the data in the database.

In order to give you a consistent view of your data, Realm only updates the active version accessed at the start of a run loop iteration. This means that if you read some data from the Realm and then block the thread on a long-running operation while writing to the Realm on other threads, the version is never updated and Realm has to hold on to intermediate versions of the data which you may not actually need, resulting in the file size growing with each write. The extra space will eventually be reused by future writes, or may be compacted — for example by calling writeCopyToPath:error: .

https://realm.io/docs/objc/latest/#file-size--tracking-of-intermediate-versions

此外,

on mobile platforms, Realm file size start at 4KB and double in size every time more than the current allocation is required. This doubling stops at 32MB, at which point the file grows in increments of 16MB. So 16MB -> 32MB -> 48MB.

https://github.com/realm/realm-cocoa/issues/2631#issuecomment-145566190

這就是爲什麼文件大小通常會比預期更大。

要優化(刪除所有可用空間)領域文件大小,您可以使用writeCopyToPath:error:方法。複製的文件將被壓縮。