【问题标题】:Callback method to Apple run loopApple 运行循环的回调方法
【发布时间】:2013-12-30 17:01:15
【问题描述】:

如何向 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

指向指针或其他东西?

【问题讨论】:

    标签: c++ objective-c macos cfrunloop


    【解决方案1】:

    documentation 没有列出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() 使其无效。

    【讨论】:

      猜你喜欢
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 1970-01-01
      • 2023-04-06
      • 2014-04-13
      • 2011-12-10
      • 1970-01-01
      相关资源
      最近更新 更多