我的应用程序 (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/