objective-cmacosmemorykeyboard-eventscgeventtap

(Mac) creating keyboard events causes memory leaks


My app's memory usage goes up permanently, each time I create a keyboard event using Quartz Event Services.

The following is the problematic code inside of an infinite loop:

int keyCode = 0;
BOOL keyDownBool = FALSE;

while (TRUE) {


    /* creating a keyboard event */

    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);

    CGEventRef keyboardEvent =
    CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCode, keyDownBool);

    CFRelease(source);
    CFRelease(keyboardEvent);



}

Instruments.app says that there are no memory leaks...

What is the problem here?

Thank you for your help!


Solution

  • Okay so the solution is pretty simple. You only need to create your CGEventSourceRef once, and then you can reuse it each time you want to post an event. Creating your CGEventSourceRefover and over again causes the "leaks" to happen.

    The proper code looks like this:

    int keyCode = 0;
    BOOL keyDownBool = FALSE;
    
    
    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);
    
    
    
    while (TRUE) {
    
    
        /* creating a keyboard event */
    
    
        CGEventRef keyEvent =
        CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCode, keyDownBool);
    
    
        CFRelease(keyEvent);
    
    
    
    }
    

    Thanks to @Willeke for the suggestion.