1

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;
}

このコードはうまく機能し、デバイスが追加されると、IONotificationPortRef を使用して IOServiceAddInterestNotification を使用し、設定された io_object_t をグローバル オブジェクトに格納します。

このコードを分析して少しリファクタリング (グローバルをクラス内のオブジェクト変数にする) を行ったところ、自分の IONotificationPortRef オブジェクトで IONotificationPortDestroy を呼び出していないことに気付きました。私はそれを呼び出す必要がありますか?また、IOServiceAddInterestNotification に割り当てられている io_object_t を使って何もしていません - そこで必要なクリーンアップはありますか?

4

1 に答える 1

0

OK、多くの Apple ドキュメントを調べた結果、通知である io_object_t に対して IOObjectRelease を実際に実行する必要があることがわかりました。参考文献をいくつか見つけましたが、最も簡単なのは、Apple Developer サイトのドキュメント「User-Mode USB Device Arbitration」にあります。

于 2012-08-03T15:58:44.827 に答える