我正在尝试向Realm数据库方案(箭头所指)添加另一个属性,同时学习如何使用迁移功能。
class FeesPaid: Object {
dynamic var fileNumber = ""
dynamic var forMonth = ""
dynamic var amount: Float = 0.0
dynamic var balance: Float = 0.0 <-------
dynamic var date = ""
}
我一直遵循Realm.io上的说明,并且已将代码复制到了第一个块中,并将其放入了位于“ AppDelegate.swift”文件中的“ application(application:didFinishLaunchingWithOptions :)”函数中。
let config = Realm.Configuration(
// Set the new schema version. This must be greater than the previously used
// version (if you've never set a schema version before, the version is 0).
schemaVersion: 1,
// Set the block which will be called automatically when opening a Realm with
// a schema version lower than the one set above
migrationBlock: { migration, oldSchemaVersion in
// We haven’t migrated anything yet, so oldSchemaVersion == 0
if (oldSchemaVersion < 1) {
// Nothing to do!
// Realm will automatically detect new properties and removed properties
// And will update the schema on disk automatically
}
}
)
// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config
// Now that we've told Realm how to handle the schema change, opening the file
// will automatically perform the migration
let clients = try! Realm()
Realm网站上此块下方的语句指出:
“至少,我们要做的就是用一个空块更新版本,以指示该模式已由Realm进行了(自动)升级。”
(上面的if语句中的注释似乎支持不需要做其他任何事情的语句。)
但是,当我运行我的应用程序时,我不断收到错误消息:
致命错误:“尝试!” 表达式意外引发错误:Error Domain = io.realm代码= 0“由于以下错误,对象类型'FeesPaid'要求进行迁移: -属性“ balance”已添加到最新的对象模型中。”由于以下错误,UserInfo = {NSLocalizedDescription =需要对对象类型“ FeesPaid”进行迁移: -属性“ balance”已添加到最新的对象模型。}:文件/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.1.101.15/src/swift/stdlib/public/core/ErrorType.swift ,第50行
那我在做什么错?
我不需要在新字段中枚举或预先填写任何值。我只需要计划中的新字段。
我将您的代码与文档中的示例和示例代码进行了比较,看起来不错。通过所有帐户,应该工作。
我唯一想到的是,Realm
在您的应用程序委托中配置该对象之前,该对象可能会在应用程序中的其他位置被调用。如果您的应用程序使用情节提要,并且视图控制器viewDidLoad
方法中包含任何领域代码,则这是可能的,因为在触发应用程序委托之前已加载了该代码。如果是这种情况,通常很容易解决,因为您需要做的只是手动设置并在application(application:didFinishLaunchingWithOptions:)
未能做到这一点,esthepiking说的是正确的。您可以在测试期间增加架构版本,或者如果您知道在开发期间架构变更将非常不稳定,则也可以在每次启动应用程序时将其删除。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句