可可Swift,在文件和目录上获取/设置隐藏(可见/不可见)标志 [英] Cocoa Swift, get/set hidden (visible/invisible) flag on files and directories
问题描述
我想测试文件系统上的文件或目录是否具有特定标志,在这种情况下为"hidden"标志,然后对其进行设置或删除.我知道可以通过命令行实现此功能,但是我想知道是否可以使用Cocoa/Swift做到这一点?
I want to test if a file or directory on the file system has a certain flag, in this case the 'hidden' flag and then set it or remove it. I know this is possible through the command line, but I was wondering if I could do it with Cocoa/Swift?
我尝试使用NSFileManager
attributesOfItemAtPath
,但是返回的对象不包含标志.
I tried using NSFileManager
attributesOfItemAtPath
, but the returned object does not contain the flags.
示例:
let fm = NSFileManager.defaultManager()
do {
let testLibrary = try fm.attributesOfItemAtPath(dataPath)
print (testLibrary)
} catch let error as NSError {
print("JSON Error: \(error.localizedDescription)")
}
返回:
["NSFileCreationDate": 2013-08-16 21:37:57 +0000,
"NSFileGroupOwnerAccountName": staff,
"NSFileType": NSFileTypeDirectory,
"NSFileSystemNumber": 16777220,
"NSFileOwnerAccountName": xjx,
"NSFileReferenceCount": 61,
"NSFileModificationDate": 2015-10-22 07:25:12 +0000,
"NSFileExtensionHidden": 0,
"NSFileSize": 2074,
"NSFileGroupOwnerAccountID": 20,
"NSFileOwnerAccountID": 501,
"NSFilePosixPermissions": 448,
"NSFileSystemFileNumber": 603923]
为了进行比较,当我在主目录中执行ls -lO
时,会看到以下内容(请注意库"上的隐藏标志):
For comparison, when I do ls -lO
in my home directory, I see the following (notice the hidden flag on 'Library'):
drwx------+ 49 xjx staff - 1666 Jan 11 19:43 Downloads
drwx------@ 28 xjx staff - 952 Jan 11 08:40 Dropbox
drwx------@ 61 xjx staff hidden 2074 Oct 22 09:25 Library
drwx------+ 7 xjx staff - 238 Apr 30 2015 Movies
drwx------+ 5 xjx staff - 170 Jun 14 2015 Music
推荐答案
以前的答案并没有完全起作用,但是它们使我以正确的方式进行工作,因此我设法找到了满足我需求的解决方案.
Previous answers didn't work completely, but they set me on the right way, so I managed to find a solution that satisfies my needs.
获取:
let myUrl = NSURL(fileURLWithPath: "my/path")
var isHidden: AnyObject?
do {
try myUrl.getResourceValue(&isHidden, forKey: NSURLIsHiddenKey)
return (isHidden as? NSNumber)?.boolValue ?? false
} catch let error as NSError {
print(error.debugDescription)
return false
}
设置:
let myUrl = NSURL(fileURLWithPath: "my/path")
do {
try libraryUrl.setResourceValue(true, forKey: NSURLIsHiddenKey)
} catch let error as NSError {
print(error.localizedDescription)
return
}
这篇关于可可Swift,在文件和目录上获取/设置隐藏(可见/不可见)标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!