最佳答案
NSURL
对象具有键 NSURLTagNamesKey
的资源。该值是一个字符串数组。
此 Swift 示例读取标签,添加标签 Foo
并将标签写回。
let url = NSURL(fileURLWithPath: "/Path/to/file.ext")
var resource : AnyObject?
do {
try url.getResourceValue(&resource, forKey: NSURLTagNamesKey)
var tags : [String]
if resource == nil {
tags = [String]()
} else {
tags = resource as! [String]
}
print(tags)
tags += ["Foo"]
try url.setResourceValue(tags, forKey: NSURLTagNamesKey)
} catch let error as NSError {
print(error)
}
<小时/>
Swift 3+ 版本有点不同。在 URL
中,tagNames
属性是仅获取的,因此需要将 URL
桥接转换为 Foundation NSURL
var url = URL(fileURLWithPath: "/Path/to/file.ext")
do {
let resourceValues = try url.resourceValues(forKeys: [.tagNamesKey])
var tags : [String]
if let tagNames = resourceValues.tagNames {
tags = tagNames
} else {
tags = [String]()
}
tags += ["Foo"]
try (url as NSURL).setResourceValue(tags, forKey: .tagNamesKey)
} catch {
print(error)
}
关于macos - 使用 swift 或 obj-c 在 cocoa 应用程序 OS X 中读取和写入文件标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38633600/