【问题标题】:IONotificationPortDestroy - to call or not to call?IONotificationPortDestroy - 打电话还是不打电话?
【发布时间】:2012-07-18 18:08:07
【问题描述】:

我有代码可以在 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 做任何事情 - 那里需要进行任何清理吗?

【问题讨论】:

    标签: objective-c macos usb iokit


    【解决方案1】:

    好的,我在查阅了很多 Apple 文档后发现的一件事是,我真的应该在通知的 io_object_t 上执行 IOObjectRelease。我找到了一些对它的引用,但最简单的是在 Apple Developer 网站上的“用户模式 ​​USB 设备仲裁”文档中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      相关资源
      最近更新 更多