ios - 带有 archiveRootObject 的 URLByAppendingPathComponent 不能正常工作?

标签 ios swift save nsurl

我目前正在 Xcode 7 和 ios 9 上使用 SpriteKit,我遇到了建议的 URLByAppendingPathComponent 方法,该方法用于访问文件的本地 url 并结合 archiveRootObject 没有将对象保存到文档目标,而是保存在数据文件夹中。这是代码

func saveData(){
   let objectToSave = SomeObject()

    let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let path = NSURL(string: docPath)
    let fp = path?.URLByAppendingPathComponent("savedObject.data")
    if NSKeyedArchiver.archiveRootObject(objectToSave, toFile: String(fp)) {
        print("Success writing to file!")
    } else {
        print("Unable to write to file!")
    }

}

不过,这会保存数据,但会保存在 Bundle 文件夹附近的 Data 文件夹中。 (虽然我还没有在真实设备上测试过)。

在调试器中,常量 fp 保存着正确的 NSURL 字符串,所以我只是不明白我做错了什么。

但是,使用 let fp = docPath + "/savedObject.data" 并随后在 archiveRootObject 函数中将对象保存在正确的位置,尽管在调试器中字符串是相同的。

我的问题是,有人可以解释一下,第一种方法有什么问题吗?

最佳答案

如今,用于此的最佳 API 是 NSFileManager。您还应该使用 NSURL path 方法而不是 String()。我会推荐这个:

if let docDir = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first,
    let filePath = docDir.URLByAppendingPathComponent("savedObject.data").filePathURL?.path
{
    // ...Write to the path
}

关于 String(x) 的更多信息:

我已经复制了 String initializer的定义如下。您可以看到它尝试了几种不同的字符串表示形式,并且主要用于调试目的——对于 NSURL 和许多其他 NSObject 子类,它调用 Obj-C description 方法。您不应依赖description 的结果。相反,您应该使用任何可用的特定情况方法,例如本例中的 path

extension String {
    /// Initialize `self` with the textual representation of `instance`.
    ///
    /// * If `T` conforms to `Streamable`, the result is obtained by
    ///   calling `instance.writeTo(s)` on an empty string s.
    /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the
    ///   result is `instance`'s `description`
    /// * Otherwise, if `T` conforms to `CustomDebugStringConvertible`,
    ///   the result is `instance`'s `debugDescription`
    /// * Otherwise, an unspecified result is supplied automatically by
    ///   the Swift standard library.
    ///
    /// - SeeAlso: `String.init<T>(reflecting: T)`
    public init<T>(_ instance: T)
    ...

关于ios - 带有 archiveRootObject 的 URLByAppendingPathComponent 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32682620/

相关文章:

c++ - 将文件作为参数从 Swift 传递给 C++ 方法

php - 授予777权限以在php中动态创建文件

iphone - 另一个 View 中的相机预览宽度问题

ios - 如何清除ImageView?

ios - XIB 和 NIB 有什么区别?

ios - Realm数据库在IOS应用中的难点

ios - 如何使用 swift 登录带有 javascript 的网站?

ios - 如何将文件添加到项目并引用它?

r - 如何在R中保存数据框

javascript - 如何使用 canvas.toDataURL() 将 Canvas 保存为图像?