无法将 ToFile 写入 NSSearchPathForDirectoriesInDomains(.CachesDirectory、.UserDomainMask、true)

Cannot writeToFile to NSSearchPathForDirectoriesInDomains(.CachesDirectory,.UserDomainMask, true)

我想保存到文件 NSSearchPathForDirectoriesInDomains(.CachesDirectory,.UserDomainMask, true)。我写了如下代码,但是它不能将文件保存在缓存目录中,它的成功变成了错误。你能告诉我如何解决这个问题吗?谢谢你的好意。

    let paths2 = NSSearchPathForDirectoriesInDomains(
        .CachesDirectory,
        .UserDomainMask, true)
    let cachesPath: AnyObject = paths2[0]

    var user:NSDictionary = [
        "Name": "Tom",
        "Address": "Tokyo",
    ]

    let success = user.writeToFile(cachesPath as! String, atomically: true)

    if success {
        println("save sucess")
    }

您正在尝试使用 Caches 目录的路径保存文件。您只能将文件写入文件路径。要创建文件路径,请将文件名附加到要保存它的目录中,如下所示:

let paths2 = NSSearchPathForDirectoriesInDomains(
    .CachesDirectory,
    .UserDomainMask, true)
let cachesPath: AnyObject = paths2[0]

var user:NSDictionary = [
    "Name": "Tom",
    "Address": "Tokyo",
]

let filePath = cachesPath.stringByAppendingPathComponent("CachedUser")
let success = user.writeToFile(filePath, atomically: true)

if success {
    println("save sucess")
}