Reputation: 956
The following code is deleting the wrong entry. I have an array that shows a list of events. in the debugger indexPath.row shows 1 (which is the entry I selected to delete. However when the view refreshes it has deleted the entry 4.
func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCellEditingStyle,
forRowAt indexPath: IndexPath) {
print(type(of: selectedRecipient))
var eventsOnArray = selectedRecipient?.events?.allObjects
guard let event = eventsOnArray?[indexPath.row] as? Event, editingStyle == .delete else {
return
}
managedContext.delete(event)
do {
try managedContext.save()
print("Deleted")
eventsOnArray?.remove(at: indexPath.row)
getEvents()
self.eventList.reloadData()
} catch let error as NSError {
print("Saving error: \(error), description: \(error.userInfo)")
}
}
Upvotes: 0
Views: 93
Reputation: 1607
Adding to @Joakim Danielson’s answer, you would add an extension for your entity to provide for an array instead of a set, like this:
extension Recipient {
var eventsArray: [Event] {
get {
if let eventSet = events as? Set<Event> {
return eventSet.sorted { (item0, item1) -> Bool in
return item0.title < item1.title
}
}
return []
}
}
}
This assumes there is a title
attribute in your Event
entity so the array returns all events sorted by title. Modify the sorted
closure according to your needs.
Upvotes: 0
Reputation: 52013
My guess here is that the order of your data source is not the same as the array you use in the code we see.
I base this on the fact that you call events?.allObjects
which suggests that events is a NSSet which is unordered and calling allObjects on it gives you an array with an undefined order. You need to have an array instead of a set so you can guarantee the same sort order of your objects through different parts of your code.
Upvotes: 1