回调方法到Apple运行循环 [英] Callback method to Apple run loop

查看:219
本文介绍了回调方法到Apple运行循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何向Apple事件侦听器添加回调方法,如:

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

CFRunLoopSourceRef IOPSNotificationCreateRunLoopSource(IOPowerSourceCallbackType callback,
                                                       void *context);

如何添加方法或块到以下方法,以便当电源更改时,我可以(我可以看到它是C ++,但是NSLog仍然在Obj-C ++中工作)类似:

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");
}

我想我需要改变:

IOPowerSourceCallbackType callback

推荐答案

文档没有列出 IOPowerSourceCallbackType 类型,但它在< IOKit / ps / IOPowerSources.h> 标头为:

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)
{
    // ...
}

您可以使用以下代码将其传递给 IOPSNotificationCreateRunLoopSource

You would pass that in to IOPSNotificationCreateRunLoopSource using code like:

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

您想仔细考虑要在哪个模式下安排源的运行循环。如果你需要在以后的时间对运行循环源( rls )做更多的事情,那么不要立即释放它。保持在一个实例变量或类似的东西,释放它,当你完成它。特别是,你可能想要使用 CFRunLoopSourceInvalidate()在某一时刻使它无效。

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.

这篇关于回调方法到Apple运行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆