Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

objective c - How can i tell if an object has a key value observer attached

if you tell an objective c object to removeObservers: for a key path and that key path has not been registered, it cracks the sads. like -

'Cannot remove an observer for the key path "theKeyPath" from because it is not registered as an observer.'

is there a way to determine if an object has a registered observer, so i can do this

if (object has observer){
  remove observer
}
else{
  go on my merry way
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put a try catch around your removeObserver call

@try{
   [someObject removeObserver:someObserver forKeyPath:somePath];
}@catch(id anException){
   //do nothing, obviously it wasn't attached because an exception was thrown
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...