简体   繁体   中英

Detect change in NSMutableOrderedSet with Swift 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:

    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:

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?

If I correctly understood logic of your code try the following (that init not needed)

  1. variant 1 - add force update

    func updateView() {

     //... other code self.objectWillChange.send()

    }

  2. variant 2 - recreate storage

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM