我想定期在iOS上压缩一个Realm实例来恢复空间.我认为该过程是将数据库复制到临时位置,然后将其复制回来并使用新的default.realm文件.
我的问题是Realm()就像一个单例并且回收对象,所以我无法真正关闭它并告诉它打开新的default.realm文件.
这里的文档(https://realm.io/docs/objc/latest/api/Classes/RLMRealm.html)建议我在autorelease {}中包装所有的Realm()调用,但它不能这么复杂.
解决方法
完全拆除所有检索到的模型访问器确实很棘手,但遗憾的是没有其他方法可以关闭一个领域.
正如您“定期”编写的那样,每个应用程序的启动可能已经足够,具体取决于您的用例.
在启动应用程序时,在专用的自动释放池中打开Realm仍然相对容易,将压缩的副本写入不同的路径并用它替换default.realm文件.
斯威夫特2.1
func compactRealm() { let defaultURL = Realm.Configuration.defaultConfiguration.fileURL! let defaultParentURL = defaultURL.URLByDeletingLastPathComponent! let compactedURL = defaultParentURL.URLByAppendingPathComponent("default-compact.realm") autoreleasepool { let realm = try! Realm() realm.writeCopyToPath(compactedURL) } try! NSFileManager.defaultManager().removeItemAtURL(defaultURL) try! NSFileManager.defaultManager().moveItemAtURL(compactedURL,toURL: defaultURL) } func application(application: UIApplication,didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { compactRealm() // further setup … return true }
Swift 3.0
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) } func application(application: UIApplication,didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { compactRealm() // further setup … return true }