我在其他地方填充了.realm文件&现在我想用它作为数据库。为了简化这个故事,让我们假设我完全遵循the manual,除了它的'最后一部分,这是可以治疗的。
问题是当我第一次启动应用程序时,.realm文件没有被复制,但是在我重新启动应用程序后(在模拟器/真实设备上),它运行良好。
我尝试引用the migration sample,说实话,这让我更加困惑,这显然是我在这里寻求帮助的原因。
这里我错了:
import RealmSwift
func bundlePath(path: String) -> String? {
let resourcePath = NSBundle.mainBundle().resourcePath as NSString?
return resourcePath?.stringByAppendingPathComponent(path)
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func openRealm() {
let defaultPath = Realm.Configuration.defaultConfiguration.path!
if let v0Path = bundlePath("names.realm") {
do {
try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
try NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath)
print("Copied.")
} catch {
print("Wasn't copied.")
}
}
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
openRealm()
let realm = try! Realm()
print("NamesCount: \(realm.objects(Names).count)")
return true
}
感谢您的时间和读这个,现在请帮帮我。我为什么看到
没有被复制。 NamesCount:0
首次启动时
复制。 NamesCount:7
第二次发布时和上?
答案 0 :(得分:3)
您在其他地方遇到问题;)
第一次try
首次运行异常,因为您还没有此文件。 copyItemAtPath
之后没有打电话。所以你有一个空的默认域文件,没有数据。
func openRealm() {
let defaultPath = Realm.Configuration.defaultConfiguration.path!
if let v0Path = bundlePath("names.realm") {
if NSFileManager.defaultManager().fileExistsAtPath(defaultPath) {
do {
try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
print("Remove old file")
} catch {
print("Wasn't removed")
}
}
do {
try NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath)
print("Copied.")
} catch {
print("Wasn't copied.")
}
}
}