领域迁移未称为 [英] Realm migration not called
问题描述
我已经向领域对象添加了一个值(我已经向WeekReport对象添加了动态var inspectorName ="),并且我正在尝试迁移领域数据库以包含该值.我正在尝试像这样在func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil)
中调用迁移块:
I've added a value to a realm object (I've added dynamic var inspectorName = "" to the WeekReport object), and I'm trying to migrate the realm database to contain that value. I'm trying to call the migration block in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil)
like this:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print("HERE")
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
migration.enumerateObjects(ofType: WeekReport.className()) { oldObject, newObject in
newObject!["inspectorName"] = ""
}
}
})
return true
}
但是似乎我的错误发生之前没有调用didFinishLaunchingWithOptions
.
But it seems that didFinishLaunchingWithOptions
isn't called before my error happens.
在多视图控制器中,我有let realm = try! Realm()
.在运行应用程序时,Xcode在这里中断:
In multiple view controller i have let realm = try! Realm()
. Here Xcode breaks when I run the app:
"由于以下错误,需要迁移: -已添加属性'WeekReport.inspectorName'."UserInfo = {NSLocalizedDescription =由于以下错误,需要迁移: -已添加属性"WeekReport.inspectorName".错误代码= 10}:文件/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-800.0.63/src/swift/
"Migration is required due to the following errors: - Property 'WeekReport.inspectorName' has been added." UserInfo={NSLocalizedDescription=Migration is required due to the following errors: - Property 'WeekReport.inspectorName' has been added., Error Code=10}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-800.0.63/src/swift/
为什么不调用迁移blick?从未打印过"HERE" ...
How come the migration blick isn't called? "HERE" is never printed...
我应该在视图控制器中以不同的方式定义领域吗?
Should I define realm in a different way in my view controllers?
推荐答案
如果在视图控制器中将let realm = try! Realm()
作为实例变量编写,则会在Storyboard中的application: didFinishLaunchingWithOptions
之前调用它.要解决此问题,可以改用lazy var realm = try! Realm()
. lazy
推迟创建实例变量,直到访问该变量为止.
If you write let realm = try! Realm()
in a view controller as an instance variable, it will be called before application: didFinishLaunchingWithOptions
from Storyboard. To resolve this, you can use lazy var realm = try! Realm()
instead. lazy
defers creating an instance variable until the variable is accessed.
这篇关于领域迁移未称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!