我正在寻求为我的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的说明进行操作,并且已经将代码复制到第一个块中并将其放入我的"application(application:didFinishLaunchingWithOptions:)"函数中,该函数位于"AppDelegate.swift"文件中 .
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网站上此块下方的声明指出:
"At the very minimum all we need to do is to update the version with an empty block to indicate that the schema has been upgraded (automatically) by Realm."
(上述if语句中的注释似乎支持此声明无需其他任何操作 . )
然而,当我运行我的应用程序时,我不断收到错误:
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=0 "Migration is required for object type 'FeesPaid' due to the following errors:
- Property 'balance' has been added to latest object model." UserInfo={NSLocalizedDescription=Migration is required for object type 'FeesPaid' due to the following errors:
- Property 'balance' has been added to latest object model.}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.1.101.15/src/swift/stdlib/public/core/ErrorType.swift, line 50
那么我做错了什么?
我不需要枚举或预先填写新字段中的任何值 . 我只需要在我的方案中使用新字段 .
1 回答
我将您的代码与文档中的示例和sample code进行了比较,看起来很好 . 所有应该工作的帐户 .
我唯一能想到的是,在应用程序委托中配置之前,可能会在应用程序的其他位置调用
Realm
对象 . 如果您的应用程序使用故事板并且您在视图控制器viewDidLoad
方法中有任何Realm代码,则可以执行此操作,因为这会在您的应用程序委托被触发之前加载 . 如果's the case, it'通常很容易解决,因为你需要做的就是手动设置并在application(application:didFinishLaunchingWithOptions:)
结束时展示你的故事板如果做不到的话,那说得好的是正确的 . 您可以在测试期间增加架构版本,或者如果您知道架构更改在开发过程中会非常不稳定,您也可以在每次启动应用时删除它 .