2012-07-18 115 views
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 - 是否有任何需要清理?

回答

0

好的,我在蘋果文檔中找到很多東西之後發現的一件事情是,我應該在通知io_object_t上真正做一個IOObjectRelease。我發現了幾個參考,但最簡單的是在Apple開發人員網站的文檔「用戶模式USB設備仲裁」中。