I get two types of information with JSON, and I add "operations" to two different classes of operation queues with addObserver (forKeyPath: "operations" ...). In the observValue function, I check if operationQueue1.operations.isEmpty, and then update my information in the user interface. I do the same with if else with operationQueue2, but when 2 operations start sometime, the application crashes with an error message: *** Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <AppName.ViewController 0x102977800> for the key path "operations" from <AppName.OperationQueue1 0x1c4a233c0> because it is not registered as an observer . 'I have no problem running only 1 operation. Any suggestions?
func getInfo1(){//runned in viewDidLoad operationQueue1.addObserver(forKeyPath:"operations"...) operationQueue1.dataTask(URL:"..."....){ DispatchQueue.main.async{ NotificationCenter.default.postNotification(NSNotification.Name(rawValue: "NewDataReceived1", userInfo:infoFromTheWebsite) } } } func NewDataReceived1(){ here I add the information to arrays to be loaded in tableView1 } HERE IS THE CODE FOR 2ND INFO WHICH IS THE SAME override func observeValue(forKeyPath keyPath: String?, ....){ if(object as? operationQueue1 == operationQueue1Class && keyPath == "operations" && context == context1){ if(operationQueue1.operations.isEmpty){ DispatchQueue.main.async{ operationQueue1..removeObserver(self, forKeyPath:"operations") Timer.scheduled("refreshingTableInformation1") } } }else if(operationQueue2....){ SAME AS OPERATION 1, BUT USING DIFFERENT FUNC TO REFRESH TABLE INFORMATION AND THE TABLES ARE DIFFERENT }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } func refreshingTableInformation1(){ tableView1.reloadData() Timer.scheduled("getInfo1", repeat:false) } func refreshingTableInformation2(){ tableView2.reloadData() Timer.scheduled("getInfo2", repeat:false) }
Sometimes it works 10 seconds and crashes, and sometimes it works more than 60 seconds, and then it crashes ...
queue swift crash key-value-observing
Bogdan bogdanov
source share