【问题标题】:Cocoa/Swift: Loop through names of folder in pathCocoa/Swift:遍历路径中文件夹的名称
【发布时间】:2015-01-25 15:44:33
【问题描述】:

我目前正在使用 swift 编写一个 os x 应用程序,但我不知道如何遍历甚至获取某个路径下所有文件夹的名称。可能是fm.enumeratorAtPath

【问题讨论】:

    标签: cocoa swift nsfilemanager


    【解决方案1】:

    我使用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.
            }
        }
    }
    

    【讨论】:

    • 这当然应该给出一般的想法。但是,它不能在 Xcode 6.1.1 中编译。
    • 感谢@MartinR,我修复了编译错误并在操场上进行了尝试。它现在可以编译和工作了。
    猜你喜欢
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多