如何将一个Realm数据库迁移到应用组?

15

最近新增在应用程序和扩展之间共享Realm数据功能,我对此感到非常兴奋。文档详细介绍了如何将默认的Realm设置为应用程序组目录,并且我已经实现了这一步骤。

以下是我遇到的问题 - 在应用程序组中,传输旧数据库到新位置的最佳方法是什么?


你不能只是使用NSFileManager移动文件吗? - segiddins
苹果建议避免使用文件协调 API,因为数据可能会损坏:https://developer.apple.com/library/ios/technotes/tn2408/_index.html - Whoa
由于只有您的应用程序能够移动它,并且您可以以原子方式执行此操作,因此您将不会出现问题。 - segiddins
听起来不错,似乎可以工作。请检查答案以确保它是正确的方法? - Whoa
在iOS 8中,您可以尝试将BusinessObject作为CocoaTouch框架。我认为将业务实体和数据放入BusinessObject是一个很好的做法。 - Solomon
@Solomon 我似乎找不到任何关于BusinessObjects的资料。你有文档链接吗? - Whoa
2个回答

13

根据@segiddins的评论,我决定使用NSFileManager将旧数据库移动到应用程序组:

    let fileManager = NSFileManager.defaultManager()

    //Cache original realm path (documents directory)
    let originalDefaultRealmPath = RLMRealm.defaultRealmPath()

    //Generate new realm path based on app group 
    let appGroupURL: NSURL = fileManager.containerURLForSecurityApplicationGroupIdentifier("group.AppGroup")!
    let realmPath = appGroupURL.path!.stringByAppendingPathComponent("default.realm")

    //Moves the realm to the new location if it hasn't been done previously
    if (fileManager.fileExistsAtPath(originalDefaultRealmPath) && !fileManager.fileExistsAtPath(realmPath)) {

        var error: NSError?
        fileManager.moveItemAtPath(originalDefaultRealmPath, toPath: realmPath, error: &error)

        if (error != nil) {
            println(error)
        }
    }

    //Set the realm path to the new directory
    RLMRealm.setDefaultRealmPath(realmPath)

-1
希望这能帮助其他读者。
https://github.com/realm/realm-cocoa/issues/4490所讨论的,您可以使用以下代码设置应用程序组路径,并使用文件管理器将现有数据库移动到上述位置。
var config = Realm.Configuration()
config.fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)!.appendingPathComponent(dbFilename)
Realm.Configuration.defaultConfiguration = config

将配置文件的fileURL设置为自定义路径并不会移动现有的Realm数据库,您只是指定要读取数据库的路径。 - Radu Ursache

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接