NSFileManager fileExistsAtPath:isDirectory和swift

时间:2014-07-11 10:54:42

标签: swift

我正在尝试了解如何在Swift中使用函数fileExistsAtPath:isDirectory:,但我完全迷失了。

这是我的代码示例:

var b:CMutablePointer<ObjCBool>?

if (fileManager.fileExistsAtPath(fullPath, isDirectory:b! )){
    // how can I use the "b" variable?!
    fileManager.createDirectoryAtURL(dirURL, withIntermediateDirectories: false, attributes: nil, error: nil)
}

我无法理解如何访问b MutablePointer的值。如果我想知道它是设置为YES还是NO怎么办?

4 个答案:

答案 0 :(得分:156)

second parameter的类型为UnsafeMutablePointer<ObjCBool>,这意味着 你必须传递ObjCBool变量的地址。例如:

var isDir : ObjCBool = false
if fileManager.fileExistsAtPath(fullPath, isDirectory:&isDir) {
    if isDir {
        // file exists and is a directory
    } else {
        // file exists and is not a directory
    }
} else {
    // file does not exist
}

Swift 3和Swift 4的更新:

let fileManager = FileManager.default
var isDir : ObjCBool = false
if fileManager.fileExists(atPath: fullPath, isDirectory:&isDir) {
    if isDir.boolValue {
        // file exists and is a directory
    } else {
        // file exists and is not a directory
    }
} else {
    // file does not exist
}

答案 1 :(得分:6)

只是使基础过载。这是我的拥有网址的

extension FileManager {

    func directoryExists(atUrl url: URL) -> Bool {
        var isDirectory: ObjCBool = false
        let exists = self.fileExists(atPath: url.path, isDirectory:&isDirectory)
        return exists && isDirectory.boolValue
    }
}

答案 2 :(得分:4)

试图改善其他答案,使其更易于使用。

extension URL {
    enum Filestatus {
        case isFile
        case isDir
        case isNot
    }

    var filestatus: Filestatus {
        get {
            let filestatus: Filestatus
            var isDir: ObjCBool = false
            if FileManager.default.fileExists(atPath: self.path, isDirectory: &isDir) {
                if isDir.boolValue {
                    // file exists and is a directory
                    filestatus = .isDir
                }
                else {
                    // file exists and is not a directory
                    filestatus = .isFile
                }
            }
            else {
                // file does not exist
                filestatus = .isNot
            }
            return filestatus
        }
    }
}

答案 3 :(得分:4)

我刚刚向FileManager添加了一个简单的扩展名,使它变得更整洁。会有所帮助吗?

extension FileManager {

    func directoryExists(_ atPath: String) -> Bool {
        var isDirectory: ObjCBool = false
        let exists = FileManager.default.fileExists(atPath: atPath, isDirectory:&isDirectory)
        return exists && isDirectory.boolValue
    }
}