快速更新一系列项目 [英] updating an array of items in realm swift

查看:149
本文介绍了快速更新一系列项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新带有数组的真实数据库的内容.我想更新存储在其中的数组,下面是我的代码

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)
}

推荐答案

如果要删除updateTodoList方法中所有TodoListModel.photos的现有元素,只需在附加附加内容之前调用update.photos.removeAll. photos输入参数.

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 .:我还重命名了您的函数及其输入参数,以匹配Swift命名约定和每个输入参数实际代表的数据.如果您的函数正在返回Void,则也无需写出返回值.

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.

这篇关于快速更新一系列项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆