所以我想要做的是,检索已经保存在Realm上的对象,修改一些属性,然后再次保存,只保留数据库上的一条记录。
继承我的代码:
让领域已经保存用户
if let user = User.query() {
user.latitude = String(latitude)
user.longitude = String(longitude)
user.save()
}
User Obj中的用户查询功能
static func query() -> User? {
return User.allObjects().toArray(User.self).first
}
func save() -> User {
RealmPersister.saveObjects([self])
return self
}
RealmPersister类func
class func saveObjects(objects: [RLMObject]?) {
autoreleasepool {
guard let objects = objects where objects.count > 0 else { return }
do {
let realm = RealmEncrypted.realm()
realm.beginWriteTransaction()
realm.addObjects(objects)
try realm.commitWriteTransaction()}
catch {
print("Realm did not write objects! \(objects)")
}
}
}
class func deleteObjects(objects: [RLMObject]?) {
autoreleasepool {
guard let objects = objects where objects.count > 0 else { return }
do {
let realm = RealmEncrypted.realm()
realm.beginWriteTransaction()
realm.deleteObjects(objects)
try realm.commitWriteTransaction()
} catch {
print("Realm did not delete objects! \(objects)")
}
}
}
答案 0 :(得分:0)
这似乎需要在User
对象上使用主键。这样,您可以通过主键快速检索同一对象,修改它,然后保存它,而不会创建重复项。