kv_nvg
Last Updated: February 25, 2016
·
927
· javierg

Use Notifications to share Gestures Events

This is a nice way to decouple your app.

Lets say you want to respond in two different places to a tap event. A good example of this, is when you want to have some analytics on tap events.

We all gonna agree that putting everything inside the action handler is a very bad idea. Maybe the Cocoa purist will say delegation will be the best option, which may be true. But I think that Notifications is another good option and very powerful if used right.

So, if You do something like:

UITapGestureRecognizer *tap = [UITapGestureRecognizer.alloc initWithTarget:self action:@selector(singleTapAction:)];
tap.numberOfTapsRequired = 1;
tap.delegate = self;

You then will have in the action a notification post:

[NSNotificationCenter. defaultCenter postNotification:@"singleTap" object:aDataObject];

This way you can add observers wherever you need them:

myObserver = [NSNotificationCenter.defaultCenter addObserverForName:@"singleTap" object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *notification){
   // Actions here
}];

Don't forget to remove your observer on the corresponding dealloc:

- (void)dealloc
{
    [NSNotificationCenter.defaultCenter removeObserver:myObserver];
}