ios - 构建预填充 Realm 数据库的最佳方式

标签 ios swift realm

我的应用程序 (iOS) 将内置大量数据(并且不会同步到服务器)。我知道我可以take a pre-filled realm database and copy it over when the app is first used ,但我不知道的是:构建预填充数据库的最佳方法是什么?

应该修改我的应用程序,通过对所有对象和关系进行硬编码来静态创建 Realm 数据库,然后从模拟器中拉取数据库:

 let car1 = Car(color: "red")
 ...
 let car230 = Car(color: "blue")

 ...
 try realm.write{
    realm.add(car1)
    ...
    realm.add(car230)
 }

或者有更明智的方法吗?

最佳答案

如果数据库始终相同,出于性能考虑,我会选择预先创建的数据库选项。但是,如果您使用数据库加密,则必须进行一些运行时修改。

要实现这一点,请查看 Realm Cocoa converter project (Swift 或 Objective-C)。您可以创建从 CSV、XLSX 和 JSON 文件格式导入的 Realm 文件。

他们的例子很清楚:

var filePaths = [String]() // Array of file paths to each CSV file to include
let destinationRealmPath = '' // Path to the folder that will hold this Realm file

// Analyze the files and produce a Realm-compatible schema
let generator =  ImportSchemaGenerator(files: filePaths)
let schema = try! generator.generate()

// Use the schema and files to create the Realm file, and import the data
let dataImporter = CSVDataImporter(files: filePaths)
try! dataImporter.import(toPath: destinationRealmPath, schema: schema)

您可以在他们的 test project 中查看更多示例.

关于ios - 构建预填充 Realm 数据库的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673370/

相关文章:

ios - 具有多个数据模型的多个 Realm

ios - 显示键盘时更新 UIKeyboardAppearance

ios - 使用 "-webkit-overflow-scrolling: touch"时停止过度滚动?

Ios 应用程序缓存 Webview 和 native 调用

Swift - 类方法中的 self.init() 未创建正确的类型

android - 由于频繁更新, Realm 大数据库大小

javascript - Realm 错误 : "JS value must be of type: number"

ios - 为什么 iOS 应用最近更改了身份验证方法?

swift - 图像压缩而不改变图像的分辨率

ios - 如何在swift中定期清除NSCache?