doptimusprime
doptimusprime

Reputation: 9411

NSWindow keyDown: crashes

In my application, I inherited NSWindow class. This is to override default key down event.

//mywindow.h
@interface TWindow: NSWindow
{
}

- (void)keyDown: (NSEvent *)pEvent;
@end


//mywindow.mm
- (void)keyDown:(NSEvent *)theEvent
{
    //Detect Control-W and Control-Q and handle them.
    unsigned short  keycode;        ///< Key code.
    NSString *      charigmtch;     ///< Character ignoring matches.
    NSString *      character;
    BOOL            cmdkeydown;     ///< check if the command key is down.
    BOOL            shiftkeydown;   ///< Check if shift key is down.

    //Get the keycode of Control-W
    keycode     = [theEvent keyCode];

    //get character ignoring match.
    charigmtch  = [theEvent charactersIgnoringModifiers];

    //get character
    character   = [theEvent characters];

    cmdkeydown      = ([[NSApp currentEvent] modifierFlags] & NSCommandKeyMask) == NSCommandKeyMask;
    shiftkeydown    = ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask) == NSShiftKeyMask;
    //Get the keycode of Control
    if(cmdkeydown && 12 == keycode && ![character compare:@"q"] && ![charigmtch compare:@"q"]) {

        //CloseWithConfirm shows message box confirming quit.
        [self CloseWithConfirm];

    } else if (keycode == 48) {
        //Tab key is pressed.

            //This AppDelegate is application delegate and also NSWindowDelegate.
            AppDelegate *  delegate;       ///< Delegate.

        //Get the delegate from the window.
        delegate = (AppDelegate *)[self delegate];

        //Shift key is not down.
        if(!shiftkeydown) {
            //Tab key is pressed.
            [delegate TabKeyPressed];
        } else {
            //Shift-Tab key is pressed.
            [delegate ShiftTabKeyPressed];
        }
    }


    //Handle the other key.
    [super keyDown:theEvent];  //Line E
}

When I run following sample test case:

void TestCase ()
{
    MyThread thread1, thread2, thread3, thread4;

    //Run thread 1
    thread1.Execute();

    //Run thread 2
    thread2.Execute();

    //Run thread 3
    thread3.Execute();

    //Run thread 4
    thread4.Execute();

}

//Following function is executed in thread function.
void Perform ()
{
    //This adds the data in table view.
    AddRowInTableView ("Test");
}

This code run fines most the time. But sometimes, it crashes at Line E marked in the code. I am not able to find the reason of this crash. Can anyone help me?

I am using Mac OS X Mavericks preview and Xcode 5 for debugging and building.

Upvotes: 1

Views: 902

Answers (1)

Parag Bafna
Parag Bafna

Reputation: 22930

Do not update UI in secondary thread. All drawing and UI events must be handled on the main thread.

Upvotes: 3

Related Questions