问题
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