Detect change in NSMutableOrderedSet with Combine

I'm trying to observe change of an NSMutableOrderedSet in my ViewModel with combine. I want to know when some element is added or removed of NSMutableOrderedSet
Some code of my ViewModel :
Code Block
class TrainingAddExerciceViewModel: ObservableObject {
@Published var exercice: Exercice?
@Published var serieHistories = NSMutableOrderedSet()
...
init(...) {
...
//Where i'm trying to observe
$serieHistories
.sink { (value) in
print(value)
}
.store(in: &self.cancellables)
}
}

This is the function I use in my ViewModel to add element to NSMutableOrderedSet :
Code Block
func add(managedObjectContext: NSManagedObjectContext) {
let newSerieHistory = ExerciceSerieHistory(context: managedObjectContext)
self.serieHistories.add(newSerieHistory)
self.updateView()
}

I have some other publisher working well with an other type (custom class).
Did I miss something ?

Thanks
Answered by langy in 624812022
I got answer :

it doesn't work with NMutableOrderedSet because it's a reference-type - a class. (https://developer.apple.com/documentation/foundation/nsmutableorderedset)

Solution is to edit add() like this :

Code Block
func add(managedObjectContext: NSManagedObjectContext) {
let newSerieHistory = ExerciceSerieHistory(context: managedObjectContext)
let newStorage = NSMutableOrderedSet(orderedSet: self.serieHistories)
newStorage.add(newSerieHistory)
self.serieHistories = newStorage // << fires publisher
self.updateView()
}

Accepted Answer
I got answer :

it doesn't work with NMutableOrderedSet because it's a reference-type - a class. (https://developer.apple.com/documentation/foundation/nsmutableorderedset)

Solution is to edit add() like this :

Code Block
func add(managedObjectContext: NSManagedObjectContext) {
let newSerieHistory = ExerciceSerieHistory(context: managedObjectContext)
let newStorage = NSMutableOrderedSet(orderedSet: self.serieHistories)
newStorage.add(newSerieHistory)
self.serieHistories = newStorage // << fires publisher
self.updateView()
}

Detect change in NSMutableOrderedSet with Combine
 
 
Q