我正在使用RealmSwift,我想为我的一个对象添加一个新的主键。
我已将Realm对象更新为此
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 String作为任何现有记录的主键。
迁移的工作原理是新的' id'字段已创建,但UUID字符串不写入记录。控制台上没有显示错误。
这是我添加到AppDelegate应用程序中的内容(application: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
}
}
})
答案 0 :(得分:0)
您已经提供的代码会在您已经打开Realm后设置迁移块的默认配置。您需要在打开默认Realm之前设置默认配置,以便使用迁移块。