NSFileManager fileExistsAtPath:isDirectory和迅速


76

我试图了解如何在fileExistsAtPath:isDirectory:Swift中使用该函数,但是我完全迷路了。

这是我的代码示例:

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)
}

我不明白如何访问bMutablePointer的值。如果我想知道它设置为YESorNO怎么办?

Answers:


176

第二个参数的类型是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
}


14
这是我见过的最奇怪的界面之一。为什么不能只有isDirectory(path :)函数?
魁北克'18年

12

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

enum Filestatus {
        case isFile
        case isDir
        case isNot
}
extension URL {
    
    
    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
        }
    }
}

我将这个答案重写为URL的扩展。
强尼

5

只是为了使基地超载。这是我的网址

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
    }
}

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
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.