0

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

CFRunLoopSourceRef IOPSNotificationCreateRunLoopSource(IOPowerSourceCallbackType callback,
                                                       void *context);

如何将方法或块添加到以下方法,以便当电源更改时我可以记录如下内容(我可以看到它是 C++,但 NSLog 在 Obj-C++ 中仍然有效)类似于:

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

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

我想我需要改变:

IOPowerSourceCallbackType callback

指向一个指针或什么的?

4

1 回答 1

0

文档没有列出IOPowerSourceCallbackType类型,但在标题中声明为<IOKit/ps/IOPowerSources.h>

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

这意味着您将回调定义为:

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

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

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

您需要仔细考虑要将源安排在哪个运行循环上以及在哪种模式下。如果您以后需要对运行循环源 ( rls) 做进一步的事情,那么不要立即释放它。将它保存在实例变量或类似的东西中,并在完成后释放它。特别是,您可能希望CFRunLoopSourceInvalidate()在某些时候使用使其无效。

于 2013-12-30T20:46:48.353 回答