"Unrecognized Selector Error" While Using Gesture Recognizer

| | August 4, 2015

I receive the following error when tapping on a view:

2015-08-04 15:42:16.236 jake-and-bailey[12158:607] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MainMenuViewController openSettingsPage]: unrecognized selector sent to instance 0x7af560f0'

I added the following gesture recognizer to that view:

Interface:

#import <UIKit/UIKit.h>

@interface OpenSettingsGestureRecognizer : UITapGestureRecognizer

@property UIViewController* viewController;

- (instancetype) initWithViewController: (UIViewController*) viewController;

@end

Implementation:

#import "OpenSettingsGestureRecognizer.h"
#import "SettingsViewController.h"

@implementation OpenSettingsGestureRecognizer

- (instancetype) initWithViewController: (UIViewController*) viewController {
    self = [super initWithTarget:viewController
                          action:@selector(openSettingsPage)];
    if (self) {
        _viewController = viewController;
    }
    return self;
}

- (void) openSettingsPage {
    if (_viewController != nil) {
        [_viewController presentViewController:[[SettingsViewController alloc] init]
                                      animated:YES
                                    completion:nil];
    }
}

@end

For whatever reason the method openSettingsPage is being called from my MainMenuViewController class rather than the OpenSettingsGestureRecognizer class.

2 Responses to “"Unrecognized Selector Error" While Using Gesture Recognizer”

  1. You’re initializing the UITapGestureRecognizer‘s target with whichever UIViewController you’re using to initialize its OpenSettingsGestureRecognizer subclass. Try changing:

    self = [super initWithTarget:viewController
                          action:@selector(openSettingsPage)];
    

    to

    self = [super initWithTarget:self
                          action:@selector(openSettingsPage)];
    

    if you want the target to be OpenSettingsGestureRecognizer instead of MainMenuViewController (which I assume this the UIViewController you’re using to initialize the gesture).

  2. Change the target to self and you’re good to go like so:

     self = [super initWithTarget:self
                              action:@selector(openSettingsPage)];
    

    Read about target-action design pattern here

Leave a Reply