updating an array of items in realm swift

杀马特。学长 韩版系。学妹 提交于 2019-12-11 19:20:12

问题


I am trying to update the content of a real database which takes an array. I would like to update the array stored in it below is my code for it

class TodoListModel: Object {

    @objc dynamic var id = UUID().uuidString
    let photos = List<Data>()
    @objc dynamic var createdDate: Date?

    override static func primaryKey() -> String? {
        return "id"
    }
    let parentCategory = LinkingObjects(fromType: CategoryModel.self, property: "items")

}

In this case, the new Data just gets added instead on replacing the previous one

func updateTodoList(update: TodoListModel, createdDate: Date, photo: Array<Data>) -> Void {
    update.createdDate = createdDate
    update.photo.append(objectsIn: photo)
}

回答1:


If you want to remove all existing elements of TodoListModel.photos in your updateTodoList method, you simply need to call update.photos.removeAll before appending the contents of the photos input argument to it.

func update(todoList: TodoListModel, createdDate: Date, photos: Array<Data>) {
    todoList.createdDate = createdDate
    todoList.photos.removeAll()
    todoList.photos.append(objectsIn: photos)
}

P.S.: I've also renamed your function and its input arguments to match the Swift naming convention and the data that each input argument actually represents. There's also no need to write out the return value if your function is returning Void.



来源:https://stackoverflow.com/questions/52761328/updating-an-array-of-items-in-realm-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!