Search code examples
objective-ccocoakeycodensevent

How to find out whether a keyCode corresponds to an actual character or a function key?


Below is my code. But how do I know whether the character is from an alphabet? (Any alphabet, not just a-z)

- (void)keyDown:(NSEvent *)theEvent
{
    NSString * const character = [theEvent charactersIgnoringModifiers];
}

Solution

  • You can use NSCharacterSet:

    - (void)keyDown:(NSEvent *)theEvent
    {
        NSString * const character = [theEvent charactersIgnoringModifiers];
        if ([character length] > 0)
        {
            unichar c = [character characterAtIndex:0];
            NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
            if ([letters characterIsMember:c])
            {
                NSLog(@"that's a letter!");
            }
        }
    }
    

    If you are calling this code frequently it might pay to store letters as an instance variable.