如何识别已挂载的外接存储卷?解决同名内外存储卷区分问题
解决方案
你当前的问题根源是仅使用本地化卷名作为唯一识别依据,而macOS允许重名存储卷存在,重名外接卷挂载时会自动在挂载路径后追加数字后缀避免冲突,我们可以改用唯一性更高的属性组合来识别卷。
核心识别逻辑优化
NSWorkspace 存储卷通知的 userInfo 中除卷名外,还提供多个无重复的属性可以使用:
NSWorkspaceVolumeURLKey:卷的挂载路径,重名卷会自动追加后缀,全局唯一NSWorkspaceVolumeIsRemovableKey:布尔值,可直接区分内置(false)和外接(true)存储NSWorkspaceVolumeUUIDKey:卷的硬件唯一标识符,格式化后固定不变,是最可靠的识别依据
优化后代码示例
-- 全局变量,存储所有已挂载外接卷的信息,可绑定到自定义UI控件 property globalRemovableVolumesList : {} on volumeMounted:aNotification set userInfo to aNotification's userInfo -- 提取卷的唯一属性 set volumeName to (NSWorkspaceVolumeLocalizedNameKey of userInfo) as text set volumePath to (NSWorkspaceVolumeURLKey of userInfo) as text set isRemovable to (NSWorkspaceVolumeIsRemovableKey of userInfo) as boolean set volumeUUID to (NSWorkspaceVolumeUUIDKey of userInfo) as text -- 识别特定名称的外接卷(解决重名区分问题) if volumeName is "Macintosh HD" and isRemovable then log "外接同名卷已挂载,路径:" & volumePath & " UUID:" & volumeUUID -- 此处写对应挂载处理逻辑 end if -- 记录所有外接卷到全局列表,供UI调用 if isRemovable then copy {name:volumeName, path:volumePath, uuid:volumeUUID} to end of globalRemovableVolumesList end if end volumeMounted: on volumeUnmounted:aNotification set userInfo to aNotification's userInfo set volumeUUID to (NSWorkspaceVolumeUUIDKey of userInfo) as text set isRemovable to (NSWorkspaceVolumeIsRemovableKey of userInfo) as boolean -- 卸载时用UUID匹配,从全局列表移除对应项 if isRemovable then repeat with i from 1 to count of globalRemovableVolumesList if uuid of item i of globalRemovableVolumesList = volumeUUID then delete item i of globalRemovableVolumesList exit repeat end if end repeat end if end volumeUnmounted:
自定义UI卸载功能实现
点击卸载按钮时,直接使用对应卷的UUID或路径执行卸载命令,完全避免重名干扰:
-- 用UUID卸载(最稳妥) on unmountVolumeByUUID:volumeUUID do shell script "diskutil unmount " & quoted form of ("UUID=" & volumeUUID) end unmountVolumeByUUID: -- 用挂载路径卸载 on unmountVolumeByPath:volumePath do shell script "diskutil unmount " & quoted form of POSIX path of volumePath end unmountVolumeByPath:
内容的提问来源于stack exchange,提问作者TheOnlyOneHere
相关产品推荐
相关产品推荐

