如何更新列表中的一个到多个内容?

时间:2015-10-07 15:23:29

标签: swift realm realm-list

假设我有一些宠物有一些宠物(有主键)。

class User : Object {
    let pets = List<Pet>()
}

现在我要更新列表中的Pets(来自API)。我该怎么办?删除所有宠物并插入新的宠物?没有像createOrUpdate()方法那样的东西。

2 个答案:

答案 0 :(得分:1)

列表上没有创建或更新语义的方法。但Realm上有一个单个对象。你可以用不同的方式利用这个事实。

如果您已经有用户并且只获得了宠物的更新列表,则需要清理不再引用的宠物,从用户中删除所有宠物,然后添加所有新宠物。

let realm = …
let user = …
let newPetList = [["name": "Rex"], ["name": "Gustav"]]

// If pets can belong only to one user, you may want to delete them by:
realm.delete(user.pets)
// Alternatively you can just remove them from the updated user:
//user.pets.removeAll()

let newPets = newPetList.map { (newPetData) in
   return realm.create(Pet, newPetData, update: true)
}
user.pets.appendContentsOf(newPets)

如果您获得完整更新的用户数据并假设您的用户拥有主键,那么您也可以直接在用户上使用创建或更新:

class User : Object {
    dynamic var id: Int
    let pets = List<Pet>()

    class func primaryKey() -> String {
        return "id"
    }
}

let userData = ["id": "23", "pets": [["name": "Rex"], ["name": "Gustav"]]]
let user = realm.create(User, userData, update: true)

但是这不会照顾为该用户清理之前创建的宠物。

答案 1 :(得分:-1)

你可以使用

object.pets = // What you want

realm.write
{
  add(object, update: true)
}

请参阅文档here

不要忘记在模型类中定义主键