Callback method to Apple run loop

795 views Asked by At

How to add a callback method to Apple event listener like:

CFRunLoopSourceRef IOPSNotificationCreateRunLoopSource(IOPowerSourceCallbackType callback,
                                                       void *context);

How do i add a method or block to the following method so that when the power source changes I can log something like below, (I can see that it is C++ but NSLog still works in Obj-C++) something like:

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{

    CFRunLoopSourceRef IOPSNotificationCreateRunLoopSource(callbackMethod(),
                                                           void *context);
}
void callbackMethod(){
    //    NSLog("No power connected"); or NSLog("Power connected");
}

I guess i need to change :

IOPowerSourceCallbackType callback

to a pointer or something?

1

There are 1 answers

0
Ken Thomases On

The documentation doesn't list the IOPowerSourceCallbackType type, but it's declared in the <IOKit/ps/IOPowerSources.h> header as:

typedef void  (*IOPowerSourceCallbackType)(void *context);

That means you would define your callback as:

void callback(void *context)
{
    // ...
}

You would pass that in to IOPSNotificationCreateRunLoopSource using code like:

CFRunLoopSourceRef rls = IOPSNotificationCreateRunLoopSource(callback, whateverValueIsMeaningfulToYourCallback);
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
CFRelease(rls);

You want to carefully consider which run loop you want to schedule the source on and in which mode. If you need to do further stuff to the run loop source (rls) at later times, then don't release it immediately. Keep it in an instance variable or something like that and release it when you're done with it. In particular, you may want to invalidate it using CFRunLoopSourceInvalidate() at some point.