如何将 Realm 属性 更改为可为空?
How to change Realm property to nullable?
如何将CalendarEvent.notes
更改为可选(可为空)?
class CalendarEvent: Object {
@objc dynamic var date: String = ""
@objc dynamic var notes: String = ""
@objc dynamic var notification: String = ""
}
Realm 数据库中已经填充了数据。
我希望在 Realm 数据库中将 notes
属性 更改为可为空。
如果我尝试 @objc dynamic var notes: String? = ""
,则会出现运行时错误,指出 Migration is required due to the following errors: - Property 'CalendarEvent.notes' has been made optional.
根据 Realm 文档,在迁移期间重命名 属性 是实现此目的的一种方法。是否可以将此 属性 更改为可空且不重命名?
您可以在迁移块中处理此问题,使用相同的 属性 名称即可。这是将非可选 first_name 属性 迁移到可选 first_name 属性.
的代码
原来的对象是这样的
class PersonClass: Object {
@objc dynamic var first_name = ""
然后我们将 属性 更改为可选
class PersonClass: Object {
@objc dynamic var first_name: String? = nil
这是执行此操作的迁移块。第一个版本是 1(具有非可选 first_name),版本 2 具有更新的对象。
let vers = UInt64(2)
let config = Realm.Configuration( schemaVersion: vers, migrationBlock: { migration, oldSchemaVersion in
print("oldSchemaVersion: \(oldSchemaVersion)")
if (oldSchemaVersion < vers) {
print(" performing migration")
migration.enumerateObjects(ofType: PersonClass.className()) { oldItem, newItem in
newItem!["first_name"] = oldItem!["first_name"]
}
}
})
这将使现有数据保持不变。我们一直在使用这种迁移,因为我们的应用程序需要更改。
如何将CalendarEvent.notes
更改为可选(可为空)?
class CalendarEvent: Object {
@objc dynamic var date: String = ""
@objc dynamic var notes: String = ""
@objc dynamic var notification: String = ""
}
Realm 数据库中已经填充了数据。
我希望在 Realm 数据库中将 notes
属性 更改为可为空。
如果我尝试 @objc dynamic var notes: String? = ""
,则会出现运行时错误,指出 Migration is required due to the following errors: - Property 'CalendarEvent.notes' has been made optional.
根据 Realm 文档,在迁移期间重命名 属性 是实现此目的的一种方法。是否可以将此 属性 更改为可空且不重命名?
您可以在迁移块中处理此问题,使用相同的 属性 名称即可。这是将非可选 first_name 属性 迁移到可选 first_name 属性.
的代码原来的对象是这样的
class PersonClass: Object {
@objc dynamic var first_name = ""
然后我们将 属性 更改为可选
class PersonClass: Object {
@objc dynamic var first_name: String? = nil
这是执行此操作的迁移块。第一个版本是 1(具有非可选 first_name),版本 2 具有更新的对象。
let vers = UInt64(2)
let config = Realm.Configuration( schemaVersion: vers, migrationBlock: { migration, oldSchemaVersion in
print("oldSchemaVersion: \(oldSchemaVersion)")
if (oldSchemaVersion < vers) {
print(" performing migration")
migration.enumerateObjects(ofType: PersonClass.className()) { oldItem, newItem in
newItem!["first_name"] = oldItem!["first_name"]
}
}
})
这将使现有数据保持不变。我们一直在使用这种迁移,因为我们的应用程序需要更改。