问题
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:
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.
来源:https://stackoverflow.com/questions/20844012/callback-method-to-apple-run-loop