如何将预填充的Default.realm文件放到设备上?

我有一个领域的文件,已经填充的数据,当应用程序加载到设备上需要在那里。

我能做些什么来将领域文件放到我的设备上进行testing,以及当有人从应用程序商店下载应用程序时,我需要做些什么来确保它已经存在?

我正在使用Swift。

将你的数据库文件添加到Xcode项目,即“preloaded.realm”确保你select添加到目标,当第一次放入你的文件 添加到目标

然后(从迁移的例子),你可以做这样的事情,将预装的文件复制到您的默认目录。 这将创build一个读/写领域

// copy over old data files for migration let defaultPath = RLMRealm.defaultRealmPath() let defaultParentPath = defaultPath.stringByDeletingLastPathComponent let v0Path = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("preloaded.realm") NSFileManager.defaultManager().removeItemAtPath(defaultPath, error: nil) NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath, error: nil) 

这是一个通用代码的链接https://github.com/realm/realm-cocoa/blob/master/examples/ios/swift-2.2/Migration/AppDelegate.swift

您首先必须创build您想要与您的应用程序一起出货的领域文件。 一旦你有了,把它添加到你的应用程序的Xcode项目,并将其复制到捆绑(Xcode应该自动执行)。

此时,应用程序应该能够访问捆绑文件(可以使用NSBundle.mainBundle()。pathForResource(_:ofType :)来获取path)。

您可以在此path中创build一个只读领域(请参阅RLMRealm(path:readOnly:error 🙂 ),或将其复制到您的Documents目录以创build一个读写领域文件。

您应该参考我们的迁移示例 ,了解有关如何执行此操作的更多详细信息。