Bri*_*ian 7 macos cocoa objective-c volumes
我有一个OS X应用程序,需要响应正在安装或卸载的卷.
我已经通过定期检索卷列表并检查更改来解决了这个问题,但我想知道是否有更好的方法.
Bri*_*ian 15
这种NSWorkspace方法正是我所寻找的那种方式.稍后几行代码,我有一个比使用计时器更好的解决方案.
-(void) monitorVolumes
{
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector: @selector(volumesChanged:) name:NSWorkspaceDidMountNotification object: nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector: @selector(volumesChanged:) name:NSWorkspaceDidUnmountNotification object:nil];
}
-(void) volumesChanged: (NSNotification*) notification
{
NSLog(@"dostuff");
}
Run Code Online (Sandbox Code Playgroud)
Ana*_*ile 10
注册通知中心你得到[[NSWorkspace sharedWorkspace] notificationCenter],然后再处理你感兴趣的通知这些卷相关的那些:NSWorkspaceDidRenameVolumeNotification,NSWorkspaceDidMountNotification,NSWorkspaceWillUnmountNotification和NSWorkspaceDidUnmountNotification.
斯威夫特 4 版本:
在 applicationDidFinishLaunching 中声明 NSWorkspace 并为挂载和卸载事件添加观察者。
let workspace = NSWorkspace.shared
workspace.notificationCenter.addObserver(self, selector: #selector(didMount(_:)), name: NSWorkspace.didMountNotification, object: nil)
workspace.notificationCenter.addObserver(self, selector: #selector(didUnMount(_:)), name: NSWorkspace.didUnmountNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)
在以下位置捕获挂载和卸载事件:
@objc func didMount(_ notification: NSNotification) {
if let devicePath = notification.userInfo!["NSDevicePath"] as? String {
print(devicePath)
}
}
@objc func didUnMount(_ notification: NSNotification) {
if let devicePath = notification.userInfo!["NSDevicePath"] as? String {
print(devicePath)
}
}
Run Code Online (Sandbox Code Playgroud)
它将打印设备路径,例如 /Volumes/EOS_DIGITAL 以下是您可以从 userInfo 中读取的常量。
NSDevicePath,
NSWorkspaceVolumeLocalizedNameKey
NSWorkspaceVolumeURLKey
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3863 次 |
| 最近记录: |