I'm getting two type of information with JSON and I'm adding "operations" to 2 different Operation Queues Classes with addObserver(forKeyPath:"operations"...).
In the function observeValue I'm checking if operationQueue1.operations.isEmpty and then I refresh my information in UI. I'm doing the same thing with if else with operationQueue2, but when the 2 operations are started in sometime the application crash with 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 don't have problem when only 1 operation is started. 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 secs and crash and sometimes works for more than 60 seconds and then crash...
OperationQueue1
even though the view controller isn't registered as an observer. This could probably occur if you the reference to the vc changed. Post your operation queue's code and where you are adding the observer. – Swordfish