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 を使って何もしていません - そこで必要なクリーンアップはありますか?