我正在开发一个应用程序,该应用程序应该检测可移动存储卸载或从 USB 强行拔出时发生的事件。我如何接收这些事件?
我已经看到 NSWorkspace
是平滑卸载设备的第一种可能性,但此类具有诸如 -unmountAndEjectDeviceAtPath:
之类的方法来卸载设备。有人可以向我指出一些检测未安装卷的示例代码吗?
最佳答案
来自 HardwareGrowler 的一段代码:
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
NSNotificationCenter *center = [workspace notificationCenter];
[center addObserver:[VolumeNotifier class] selector:@selector(volumeDidMount:) name:NSWorkspaceDidMountNotification object:nil];
[center addObserver:[VolumeNotifier class] selector:@selector(volumeDidUnmount:) name:NSWorkspaceDidUnmountNotification object:nil];
[center addObserver:[VolumeNotifier class] selector:@selector(volumeWillUnmount:) name:NSWorkspaceWillUnmountNotification object:nil];
然后您需要实现对通知使用react的方法
+ (void) volumeDidUnmount:(NSNotification *)aNotification;
{
...
}
对于整个实现请查看 http://growl.info/source.php
在源包中,转到 Extras/HardwareGrowler 并查看 VolumeNotifier.h/m
更新:
彼得斯的回答比这个更好。如果您遇到此问题,请考虑使用磁盘仲裁框架。
关于cocoa - 检测可移动存储何时卸载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1408216/