我已经为一个领域对象添加了一个值(我已将动态var inspectorName =""添加到WeekReport对象中),我正在尝试迁移领域数据库以包含该值.我试图func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil)
像这样调用迁移块:
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
在我的错误发生之前没有调用.
在多视图控制器中我有let realm = try! Realm()
.我运行应用程序时Xcode中断了:
"由于以下错误,需要迁移: - 已添加属性'WeekReport.inspectorName'." UserInfo = {NSLocalizedDescription =由于以下错误而需要迁移: - 已添加属性'WeekReport.inspectorName'.,错误代码= 10}:file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang- 800.0.63/src目录/快捷/
怎么没有调用迁移blick?"HERE"从未打印过......
我应该在视图控制器中以不同的方式定义领域吗?
如果您将let realm = try! Realm()
视图控制器作为实例变量编写,它将在application: didFinishLaunchingWithOptions
Storyboard 之前被调用。要解决此问题,可以lazy var realm = try! Realm()
改用。lazy
推迟创建实例变量,直到访问该变量为止。