Max*_*Max 15 xcode realm ios swift
我正在使用swift开发iOS应用程序,并选择Realm作为它的数据库解决方案.我使用realm docs中的write/add函数在AppDelegate中编写了默认数据,它工作得很好.所以在第一次启动后,我有一个带有初始数据的*.realm文件.在Realm文档中,我找到了一个名为"使用应用程序捆绑领域"的部分,我将*.realm文件添加到项目中并在编写时构建阶段.
我无法理解接下来应该做什么(以及压缩*.realm文件的部分内容).我试图理解迁移示例中的代码,但我不太了解Obj-C.
请尽可能明确地将带有初始数据的*.realm文件添加到swift ios项目中,并在首次启动时将此数据加载到Realm数据库中.
pte*_*fil 22
openRealm在AppDelegate中实现此功能并调用它
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...
openRealm()
return true
}
func openRealm() {
let defaultRealmPath = Realm.defaultPath
let bundleReamPath = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("default.realm")
if !NSFileManager.defaultManager().fileExistsAtPath(defaultRealmPath) {
NSFileManager.defaultManager().copyItemAtPath(bundleReamPath!, toPath: defaultRealmPath, error: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
它会将您捆绑在应用程序中的领域文件复制到默认领域路径(如果它尚不存在).之后,您通常使用Realm,就像之前使用的那样.
还有你在Swift中谈到的Migration示例.
在Swift 3.0.1中,您可能更喜欢这样:
let defaultRealmPath = Realm.Configuration.defaultConfiguration.fileURL!
let bundleRealmPath = Bundle.main.url(forResource: "seeds", withExtension: "realm")
if !FileManager.default.fileExists(atPath: defaultRealmPath.absoluteString) {
do {
try FileManager.default.copyItem(at: bundleRealmPath!, to: defaultRealmPath)
} catch let error {
print("error copying seeds: \(error)")
}
}
Run Code Online (Sandbox Code Playgroud)
(但请注意选项)
| 归档时间: |
|
| 查看次数: |
6917 次 |
| 最近记录: |