[英]Best Way to Build a Pre-Filled Realm Database
我的应用(iOS)将内置大量数据(并且不会同步到服务器)。 我知道我可以获取一个预填充的领域数据库,并在首次使用该应用程序时将其复制过来 ,但是我不知道的是: 构建该预填充数据库的最佳方法是什么?
应该修改我的应用程序,通过对所有对象和关系进行硬编码来静态创建领域数据库,然后从模拟器中提取数据库:
let car1 = Car(color: "red")
...
let car230 = Car(color: "blue")
...
try realm.write{
realm.add(car1)
...
realm.add(car230)
}
还是有一个更明智的方法?
如果数据库将始终保持不变,出于性能考虑,我会选择预先创建的数据库选项。 但是,如果使用数据库加密,则必须进行一些运行时修改。
要实现这一目标,请查看Realm Cocoa转换器项目 (Swift或Objective-C)。 您可以创建从CSV,XLSX和JSON文件格式导入的领域文件。
他们的例子很清楚:
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)
您可以在他们的测试项目中查看更多示例。
您可以创建一个简单的应用程序(可能是同一Xcode工作空间中的新目标),仅用于预先填充Realm数据库,在模拟器上运行它,打开系统上的sim文件夹,然后将Realm文件从此处拖动到主项目中。 然后,在主应用程序启动时,将文件从捆绑软件复制到更合适的位置(例如documents文件夹)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.