【发布时间】:2016-05-29 21:19:01
【问题描述】:
我正在使用 RealmSwift,我想为我的一个对象添加一个新的主键。
我已将领域对象更新为此
class Trip: Object {
dynamic var id = ""
dynamic var start = ""
dynamic var startAddress = ""
dynamic var end = ""
dynamic var endAddress = ""
dynamic var purpose = ""
dynamic var distance = 0.0
dynamic var tripDate = NSDate()
dynamic var month = 0
dynamic var year = 0
dynamic var isWalking = false
dynamic var isReturn = false
func primaryKey() -> String {
return id
}
}
现在我想迁移到新版本并插入一个 UUID 字符串作为任何现有记录的主键。
迁移的工作原理是创建了新的“id”字段,但 UUID 字符串没有写入记录。控制台上没有显示错误。
这是我添加到我的 AppDelegate 应用程序的内容(应用程序:didFinishLaunchingWithOptions:)
我一定遗漏了什么,但我无法从 Realm 网站上的文档或示例中确定什么。
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 realm = try! Realm()
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
// The enumerate(_:_:) method iterates
// over every Trip object stored in the Realm file
migration.enumerate(Trip.className()) { oldObject, newObject in
let id = NSUUID().UUIDString
newObject!["id"] = id
}
}
})
【问题讨论】:
-
您提供的代码会在您打开 Realm 后使用您的迁移块设置默认配置。您需要在打开默认 Realm 之前设置默认配置,以便使用迁移块。这只是问题中的复制粘贴错误,还是反映了您正在测试的代码?
-
是的,我知道我现在做了什么。在我打开 Realm 之后,我的配置块太多了,其中包含我的迁移人口。我只是将迁移块移到第一个并完全删除了第二个配置块,它现在可以工作了。
-
我已将我的评论作为答案重新发布,因为它解决了您的问题。
标签: swift realm database-migration