快速更新一系列项目 [英] updating an array of items in realm swift
问题描述
我正在尝试更新带有数组的真实数据库的内容.我想更新存储在其中的数组,下面是我的代码
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屋!