【发布时间】:2015-01-25 15:44:33
【问题描述】:
我目前正在使用 swift 编写一个 os x 应用程序,但我不知道如何遍历甚至获取某个路径下所有文件夹的名称。可能是fm.enumeratorAtPath?
【问题讨论】:
标签: cocoa swift nsfilemanager
我目前正在使用 swift 编写一个 os x 应用程序,但我不知道如何遍历甚至获取某个路径下所有文件夹的名称。可能是fm.enumeratorAtPath?
【问题讨论】:
标签: cocoa swift nsfilemanager
我使用enumeratorAtURL。下面是一些代码,展示了如何打印用户主目录中的目录的示例。
if let dirURL = NSURL(fileURLWithPath: NSHomeDirectory()) {
let keys = [NSURLIsDirectoryKey, NSURLLocalizedNameKey]
let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtURL(
dirURL,
includingPropertiesForKeys: keys,
options: (NSDirectoryEnumerationOptions.SkipsPackageDescendants |
NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants |
NSDirectoryEnumerationOptions.SkipsHiddenFiles),
errorHandler: {(url, error) -> Bool in
return true
}
)
while let element = enumerator?.nextObject() as? NSURL {
var getter: AnyObject?
element.getResourceValue(&getter, forKey: NSURLIsDirectoryKey, error: nil)
let isDirectory = getter! as Bool
element.getResourceValue(&getter, forKey: NSURLLocalizedNameKey, error: nil)
let itemName = getter! as String
if isDirectory {
println("\(itemName) is a directory in \(dirURL.absoluteString)")
//do something with element here.
}
}
}
【讨论】: