Search code examples
objective-cautomatic-ref-countingnseventcgeventtap

Is it safe to create `NSEvent object` then `CGEventPost` the `[ev CGEvent]` then exit the method?


I have the following Objective-C snippet:

void toggle()
{
    NSEvent* down_event = [NSEvent keyEventWithType: NSEventTypeKeyDown
                                           location: NSZeroPoint
                                      modifierFlags: 0
                                          timestamp: 0.0
                                       windowNumber: 0
                                            context: nil
                                         characters: @" "
                        charactersIgnoringModifiers: @" "
                                          isARepeat: false
                                            keyCode: kVK_Space ];


    CGEventPost(kCGHIDEventTap, [down_event CGEvent]);
}

The project is ARC enabled.

Is this safe, or am I running the gauntlet of an occasional memory access error?

I'm worried that the NSObject may be garbage collected while the system is still making use of its CGEvent.


Solution

  • Yes it is safe. The documentation for the CGEvent property states:

    The CGEventRef opaque type returned is autoreleased. If no CGEventRef object corresponding to the NSEvent object can be created, this method returns NULL.

    This tells you that a new CGEvent is created that corresponds to the NSEvent. If there was a dangerous dependency, e.g. the return value contained an unsafe reference to the original object that would be noted (there was/are methods that did/do that and were/are so documented [yes, I haven't checked if any still exist]).

    BTW: if you grew up in the ARC age and do not know about "autoreleased" do not concern yourself, ARC knows and will do the right thing.