NSNotification - observer with multiple events to trigger

79 views Asked by At

As it stands, NSNotifications allow for a target-action mechanism in response to one post / event.

I would like to have a notification which triggers an action (runs a function) only after two events have been triggered.

The scenario is that I have two asynchronous processes which need to complete before I can call the function. Perhaps I'm missing something, but I haven't found a way to do this. Or maybe I'm not thinking of an obvious reason why this would be a really bad idea?

Also, some of my terminology may be off, so please feel free to edit and fix it.

1

There are 1 answers

1
Sven On BEST ANSWER

There are many possibilities on how you can implement this. They all center around keeping track of which processes are finished. The best way depends on how your background processes are implemented.

If you are using NSOperationQueue you could add a third operation that has the other two operations as a dependency. That way you won't have to take care of notifications at all.

Otherwise you can can count how many operations have finished and execute your code when the counter reaches the right value. GCD has dispatch groups as a nice abstraction for this.

First you create a dispatch group:

let group = dispatch_group_create()

Then you enter the group for each background process:

dispatch_group_enter(group)

Finally you can register an block that gets called when the group becomes empty, that is when each dispatch_group_enter is balanced by an dispatch_group_leave:

dispatch_group_notify(group, dispatch_get_main_queue()) {
   // All processes are done.
}

After each of your processes finish you leave the group again:

dispatch_group_leave(group)

It's important to call dispatch_group_enter before calling dispatch_group_notify or your block will be scheduled immediately as the group is already empty.

After your notify block was executed you can reuse the queue or discard it.