Callback method to Apple run loop

心已入冬 提交于 2019-12-13 20:57:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!