2016-06-07 72 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:方法。复制的文件将被压缩。