NSFileManager fileExistsAtPath:isDirectory和swift

Mat*_*oal 66 swift

我试图了解如何使用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)
}
Run Code Online (Sandbox Code Playgroud)

我无法理解如何访问bMutablePointer 的值.如果我想知道它是否设置YES或者NO怎么办?

Mar*_*n R 164

第二参数具有类型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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

  • 这是我见过的最奇怪的接口之一.为什么不能只有一个isDirectory(路径:)函数? (8认同)

Jon*_*nny 7

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

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


jef*_*igy 6

只是为了超载基地。这是我的,需要一个 URL

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
    }
}
Run Code Online (Sandbox Code Playgroud)


Kar*_*thy 5

我刚刚为 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
    }
}
Run Code Online (Sandbox Code Playgroud)