Sunday, November 20, 2011

Meta: old comments published, sorry.

I just realized I had not moderated comments in six million years.

So I did, and published the non-spammy ones. In case there is some kind of notification system and you get an e-mail that your comment from 1932 has been published on this blog: my apologies for the tardiness.

UITapGestureRecognizer and “unrecognized selector sent to instance” errors.

This is just a very quick note for search engine posterity, in case anybody has the same frustrating problem I had today.

I am implementing some gestures for an iOS art app (as in a work of media art, the "medium" of which is an iPhone/iPad application). I was following the "Event Handling Guide for iOS" from Apple.

After much Googling and some very informative stops at StackOverflow, I had got basically nowhere. Everything seemed right, my code conformed tightly to the tutorial and to everyone else’s, and everybody else who found a solution had obviously solved a very different core problem than I was facing. What could be wrong?!

It turns out the problem was as simple as:

-(void) handleTap
{
    NSLog(@"*** GOT A TAP ***");
}
    

Now, in real life you would almost never use a method as dumb and simple as that, but when setting up your classes for initial hacking and debugging you just might. According to the tutorial, it should work:

The action methods for handling gestures—and the selector for identifying them—are expected to conform to one of two signatures:
- (void)handleGesture
- (void)handleGesture:(UIGestureRecognizer *)sender

Silly programmer, tricks are for kids! The standard-issue selector looks for only the second signature, and if it doesn’t find it you get the error whenever you tap: unrecognized selector sent to instance! boo!

The solution, then, is to declare and implement the method with the argument. That works fine.

-(void) handleTap: (UIGestureRecognizer *)sender
{
    NSLog(@"*** GOT A TAP ***");
}
    

To be fair, Apple has an enormous amount of documentation available online, and it’s not so shocking that a tutorial is out of date. For us iOS newbies it’s frustrating, but I don’t think anybody else is doing a better job of this at the moment.