ios - 在应用程序运行时替换 Realm 文件

标签 ios swift realm

为了实现备份/恢复功能,我删除了现有的 Realm 数据库文件,并将其替换为同名的新数据库文件。但是,在应用程序仍在运行的情况下,它看不到新数据库文件的内容。如果我退出并重新启动应用程序,它会看到新数据库文件的内容。有没有什么方法可以让应用程序在不重新启动的情况下看到新内容?

最佳答案

就像从磁盘中删除 Realm 文件一样,如果您的应用程序当前没有打开 Realm 文件,则替换磁盘上的 Realm 文件是安全的。

来自 Realm 关于 Deleting Realm files 的文档:

Because Realm avoids copying data into memory except when absolutely required, all objects managed by a Realm contain references to the file on disk, and must be deallocated before the file can be safely deleted. This includes all objects read from (or added to) the Realm, all List, Results, and ThreadSafeReference objects, and the Realm itself.

In practice, this means that deleting a Realm file should be done either on application startup before you have opened the Realm, or after only opening the Realm within an explicit autorelease pool, which ensures that all of the Realm objects will have been deallocated.

这样做的原因是 Realm 在内存中维护打开文件的缓存,因此尝试打开一个已经打开的文件将导致返回对已打开文件的引用。这个打开的文件将继续引用磁盘上的原始文件,即使它已被替换。确保已清除对 Realm 访问器对象的所有引用意味着 Realm 将不会返回现有的打开文件,而是从磁盘打开文件。

换句话说,您必须确保没有对 Realm 访问器对象的引用(RealmResultsThreadSafeReference Object 实例)在您尝试替换 Realm 文件时。您还必须确保您所做的任何引用都已被释放(即,它们不会在调度队列的默认自动释放池中徘徊)。

另一种可能更易于管理的方法是在您尝试重新打开已恢复的文件时使用不同的路径。由于您正在访问磁盘上的不同路径,因此您一定会打开新文件。你仍然需要确保你没有引用 Realm 的访问器对象,否则你会得到新旧数据的奇怪混合,但确保访问器对象被释放并不是那么重要。

关于ios - 在应用程序运行时替换 Realm 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45772154/

相关文章:

ios - Realm 不存储 iOS 中的数据

android - 什么是 Realm DB 中的托管/非托管对象?

ios - 如何更改 UICollectionViewCell 中 UILabel 的值?

ios - 具有渐变边框和圆角的 UIButton

swift - (WkWebView) 当我通过输入标签上传文件时,它发生了问题

ios - 在 IOS/Swift 中创建文本字段集合

ios - 直接使用 Realm 对象还是映射到对象类?

ios - 是否有可能有一个 SCNNode 是透明的,但它遮挡了它后面的任何对象?

objective-c - UINavigationBar 不旋转

ios - sqlite数据库只更新1条记录