在OS X Finder中有评论'文件属性。可以通过添加“评论”来查找它。右键单击文件或文件夹并选择“获取信息”后的列或编辑/选中。
如何在swift或objective-c中读取此值?
我已经检查了NSURL,但似乎没有一个是正确的
答案 0 :(得分:5)
请勿使用低级扩展属性API来读取Spotlight元数据。为此提供了适当的Spotlight API。 (它被称为文件元数据API。)不仅令人痛苦,还不能保证Apple会继续使用相同的扩展属性来存储这些信息。
使用MDItemCreateWithURL()
为文件创建MDItem
。将MDItemCopyAttribute()
与kMDItemFinderComment
一起使用,即可获取该项目的Finder评论。
答案 1 :(得分:3)
将各个部分放在一起(Ken Thomases阅读上面的答案并撰写答案link)您可以使用带有getter和setter的计算属性扩展URL,以便对文件进行读/写注释:
更新: Xcode 8.2.1•Swift 3.0.2
extension URL {
var finderComment: String? {
get {
guard isFileURL else { return nil }
return MDItemCopyAttribute(MDItemCreateWithURL(kCFAllocatorDefault, self as CFURL), kMDItemFinderComment) as? String
}
set {
guard isFileURL, let newValue = newValue else { return }
let script = "tell application \"Finder\"\n" +
String(format: "set filePath to \"%@\" as posix file \n", absoluteString) +
String(format: "set comment of (filePath as alias) to \"%@\" \n", newValue) +
"end tell"
guard let appleScript = NSAppleScript(source: script) else { return }
var error: NSDictionary?
appleScript.executeAndReturnError(&error)
if let error = error {
print(error[NSAppleScript.errorAppName] as! String)
print(error[NSAppleScript.errorBriefMessage] as! String)
print(error[NSAppleScript.errorMessage] as! String)
print(error[NSAppleScript.errorNumber] as! NSNumber)
print(error[NSAppleScript.errorRange] as! NSRange)
}
}
}
}
Xcode 7.3.1•Swift 2.2.1
extension NSURL {
var finderComment: String? {
get {
guard fileURL else { return nil }
return MDItemCopyAttribute(MDItemCreateWithURL(kCFAllocatorDefault, self), kMDItemFinderComment) as? String
}
set {
guard let newValue = newValue where fileURL else { return }
let script = "tell application \"Finder\"\n" +
String(format: "set filePath to \"%@\" as posix file \n", absoluteString) +
String(format: "set comment of (filePath as alias) to \"%@\" \n", newValue) +
"end tell"
guard let appleScript = NSAppleScript(source: script) else { return }
var error: NSDictionary?
appleScript.executeAndReturnError(&error)
if let error = error {
print(error[NSAppleScriptErrorAppName] as! String)
print(error[NSAppleScriptErrorBriefMessage] as! String)
print(error[NSAppleScriptErrorMessage] as! String)
print(error[NSAppleScriptErrorNumber] as! NSNumber)
print(error[NSAppleScriptErrorRange] as! NSRange)
}
}
}
}