1
我有代码在OS X 10.7.4上使用XCode 4.3.3设置USB设备添加/删除通知。对于myVid和myPid一个USB设备,它是相当样板:IONotificationPortDestroy - 打电话还是不打电话?
// 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 - 是否有任何需要清理?