我有一个名为Person的Realm模型:
class Person: Object {
static let sharedInstance = Person()
dynamic var tableId:Int = 1453
dynamic var verificationCode = ""
dynamic var userId = ""
dynamic var phoneNumber = ""
dynamic var userName = ""
dynamic var registered: Bool = false
dynamic var userPhoto: NSData = NSData()
override class func primaryKey() -> String? {
return "tableId"
}
func save(isUpdate: Bool) {
do {
let realm = try Realm()
try realm.write {
realm.add(self, update: isUpdate)
}
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}
首先我保存了一些值:
func addTask(){
personObject.tableId = 1453
personObject.phoneNumber = "+60176336055"
personObject.verificationCode = "112"
personObject.userId = "r456666vhffg547567bg55"
personObject.registered = false
personObject.save(isUpdate: false)
}
以后我使用“update”方法为其他列添加值:
func update() {
personObject.tableId = 1453
personObject.registered = true
personObject.userName = self.usernameText.text!
if self.chosenImage != nil, let imageData = self.chosenImage.jpeg(.lowest) as NSData? {
personObject.userPhoto = imageData
}
personObject.save(isUpdate: true)
}
但是在我更新我的模型后,它会将旧值设置为空,我不想更新但保留它们。有没有办法更新行而不再传递所有现有值?我感谢任何帮助。谢谢。
答案 0 :(得分:3)
您可以通过id(如果存在)查询对象并在事务中修改其属性,而不是插入正确设置了所有字段的非托管副本。如果它不存在,则应首先将非托管副本添加到Realm。
autoreleasepool {
let realm = try! Realm()
try! realm.write {
let person = realm.objects(Person.self).filter(NSPredicate(format: "tableId = %@", tableId).first;
person.userName = usernameText;
}
}