我有代码在 OS X 10.7.4 上使用 XCode 4.3.3 设置 USB 设备添加/删除通知。对于带有 myVid 和 myPid 的 USB 设备,它是非常样板:
// Global declarations somewhere near the top of the file.
IONotificationPortRef g_notificationPort= NULL;
io_object_t g_notification= 0;
io_iterator_t g_iteratorAdded= 0;
.
.
.
- (BOOL)setupDeviceNotification
{
// Set up matching dictionary.
NSMutableDictionary* matchingDictionary= (NSMutableDictionary*)IOServiceMatching(kIOUSBDeviceClassName);
[matchingDictionary setObject:[NSNumber numberWithLong:myVid] forKey:[NSString stringWithUTF8String:kUSBVendorID]];
[matchingDictionary setObject:[NSNumber numberWithLong:myPid] forKey:[NSString stringWithUTF8String:kUSBProductID]];
// Create a run loop source for the notification object.
g_notificationPort= IONotificationPortCreate(kIOMasterPortDefault);
CFRunLoopSourceRef notificationRunLoopSource= IONotificationPortGetRunLoopSource(g_notificationPort);
CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);
// Set up a notification callback for device addition on first match.
kern_return_t kRet= IOServiceAddMatchingNotification(g_notificationPort, kIOFirstMatchNotification, (CFMutableDictionaryRef)matchingDictionary, deviceAddedCallback, (void*)self, &g_iteratorAdded);
// Rudimentary error handling.
if(KERN_SUCCESS != kRet)
{
[matchingDictionary release];
return FALSE;
}
// Arm the notification and check for existing devices.
[self deviceWasAdded:g_iteratorAdded];
return TRUE;
}
此代码运行良好,当添加设备时,我使用 IOServiceAddInterestNotification 使用 IONotificationPortRef 并将设置的 io_object_t 存储在全局对象中。
在分析此代码以进行一些重构(将全局变量转换为类中的对象变量)后,我意识到我从未在我的 IONotificationPortRef 对象上调用 IONotificationPortDestroy。我应该叫它吗?另外,我没有对 IOServiceAddInterestNotification 中分配的 io_object_t 做任何事情 - 那里需要清理吗?