处理回调

shr*_*ads 5 cocoa objective-c

我在Objective-C类中有一个方法.它有2个用C编写的回调函数.类指针即self传递给这些函数void *.在C函数中,我创建了一个类型为class的指针并分配void *参数.第一个回调函数成功执行.但void *指针变为nil第二个回调函数.请注意,我没有在第一个回调中调整指针但仍然进入nil第二个回调.

什么想法可能会出错?

例如:

kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification,
                                      matchingDict, RawDeviceAdded, NULL,
                                      &gRawAddedIter);

RawDeviceAdded(NULL, gRawAddedIter, self);
Run Code Online (Sandbox Code Playgroud)

这很好用.但是下面的功能收到selfnil.

kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification,
                                      matchingDict, BulkTestDeviceAdded, NULL,
                                      &gBulkTestAddedIter);

BulkTestDeviceAdded(NULL, gBulkTestAddedIter, self);
Run Code Online (Sandbox Code Playgroud)

Boa*_*ler 11

您的问题是否特别与IOKit回调例程有关?你给出的具体例子的问题是IOServiceMatchingCallback只需要2个参数,而不是3.你需要你的RawDeviceAdded()和BulkTestDeviceAdded()回调函数来匹配IOServiceMatchingCallback原型并接受self作为第一个参数(refCon),而不是第三个.此外,您需要传入self作为IOServiceAddMatchingNotification()的倒数第二个参数,以便通过回调将其传递给您.

在Objective-C代码中处理C回调的常用方法就是使用一个静态函数将回调转发给您的实例.因此,您的示例回调代码如下所示:

static RawDeviceAdded(void* refcon, io_iterator_t iterator)
{
    [(MyClass*)refcon rawDeviceAdded:iterator];
}

@implementation MyClass
- (void)setupCallbacks
{
    // ... all preceding setup snipped
    kr = IOServiceAddMatchingNotification(gNotifyPort,kIOFirstMatchNotification, matchingDict,RawDeviceAdded,(void*)self,&gRawAddedIter );
    // call the callback method once to 'arm' the iterator
    [self rawDeviceAdded:gRawAddedIterator];
}
- (void)rawDeviceAdded:(io_iterator_t)iterator
{
    // take care of the iterator here, making sure to complete iteration to re-arm it
}
@end
Run Code Online (Sandbox Code Playgroud)


Rob*_*uld 0

Objective-C 选择器的用途如下: http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSInitationOperation_Class

API 不是很直观,但是一旦理解就很好了

您可能还需要进行一些重构,现在可能有更好的方法,但是当我遇到这个问题时,我的解决方案是重构并使用 InvoationOperation。