0

Posting notifications from the NSNotificationCenter on the certain button click event Hence When I have rapid button events The notification is being called that many times leads to the many problems. I want to cancel the previous posted notification when rapid events happening. How to do with below code.

func buttonClick() {    
// I want to cancel the previous Event here
NSNotificationCenter.defaultCenter().postNotificationName("Event", object: self)
}

UPDATE:

Let me explain clearly what I want actually I have one observer method when a button click is happened from that I want to post the some notifications to control some UI elements like changing the button image. The problem is When I hit the button rapidly observer getting called many times as well my notifications being posted on the same count hence UI is blinking I can't have control on the Observer on the button click event I have only control over the posted event from my side.

Any help much appreciated.

Vishnuvardhan
  • 5,081
  • 1
  • 17
  • 33

1 Answers1

1

NSNotificationCenter.post() is synchronous. It does not return until all the observers have performed their actions. So there is no way to cancel it; there is no queue.

If you are generating a lot of notifications very close to each other (especially within the same run-loop cycle), you can coalesce them using NSNotificationQueue with enqueueNotification. Generally something like:

NSNotificationQueue.defaultQueue().enqueNotification(note, postingStyle: .whenIdle)

That said, if this is tied to a button click (a human interaction), then the notifications are likely very far apart in computer terms. Half a second is an eternity in computer terms. If that's the case, you're likely better-off controlling this first at the UI, by disabling the button until you're willing to accept another click (for example with button.enabled = false).

It is possible to write a wrapper that coalesces operations over any arbitrary period, but this is likely to be confusing in your case, because the user will be able to click something that the system will ignore. If that's still what you want, I'll see if I can find an example of a coalescing trampoline (I've written them in ObjC, but I don't have a Swift example on hand).

Rob Napier
  • 286,113
  • 34
  • 456
  • 610