问题描述
我正在使用 NSFileManager
的方法 createDirectoryAtPath:withIntermediateDirectories:attributes:error:
in Swift。
I'm trying to use NSFileManager
's method createDirectoryAtPath:withIntermediateDirectories:attributes:error:
in Swift.
问题是我不知道这个功能是否会在错误的情况下抛出。这是否记录在任何地方?如果是,在哪里?
The problem is that I have no idea what this function throws
in case of error. Is this documented anywhere? If yes, where?
推荐答案
当Swift文档说一个函数 throws
,这意味着它会抛出一个 NSError
。
When the Swift docs says a function throws
, they mean that it throws an NSError
.
考虑以下 do-try -catch
flow:
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
do {
try NSFileManager.defaultManager().createDirectoryAtPath(documentsPath, withIntermediateDirectories: false, attributes: nil)
} catch {
print(error)
print(error.dynamicType)
}
createDirectoryAtPath
将失败,因为文档目录已经存在。记录错误
中的 dynamicType
表明它实际上是一个 NSError
object:
createDirectoryAtPath
will fail because the documents directory already exists. Logging the dynamicType
of the error
shows that it is in fact an NSError
object:
Error Domain=NSCocoaErrorDomain Code=516 "The file "Documents" couldn’t be saved in the folder "35B0B3BF-D502-4BA0-A991-D07568AB87C6" because a file with the same name already exists." UserInfo={NSFilePath=/Users/jal/Library/Developer/CoreSimulator/Devices/E8A35774-C9B7-42F0-93F1-8103FBBC7118/data/Containers/Data/Application/35B0B3BF-D502-4BA0-A991-D07568AB87C6/Documents, NSUnderlyingError=0x7fa88bd14410 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}
NSError
这篇关于用Swift创建一个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!