Search code examples
objective-ccocoaevent-handlingosc

Can I call a method without triggering its event listeners?


Is there any sort of flag or way to call a method without triggering any event handlers?

FOR EXAMPLE I'm handling a controlTextDidChange method and checking to see if the character returned by a keystroke is valid. If it's not, I remove it; if it is, I append a word. The problem is that when I change the text while in controlTextDidChange, controlTextDidChange is called again and the program will loop indefinitely. I know I can use an instance variable to get around this, but is there any sort of flag or way to call a method without triggering any event handlers?


Solution

  • To expand the comment into a quick answer.

    You have a method that issues a notification by design. You want it to not issue that notification. You don't have an alternative available that does the same thing w/o the notification. If you want it to never issue that notification, and you have access to the code for the method, you could swizzle the method to a version where you've just commented out the notification. Of course, if you had the code, you could just add another method, and call that one. So you don't have the code, and all that's moot.

    Can't you just bracket that invocation in code that removes the listener and then restores the listener? In other words, psuedocode like this:

    [self.controlThingy removeObserver:self]
    [self.controlThingy myMethod]
    [self.controlThingy addObserver:self]
    

    You've then made self deaf to notifications for that one invocation of myMethod. I've done similar things with bindings and KVO.