ios - 为什么这个 plist 读/写失败?

标签 ios swift plist

我正在学习 iOS 教程,但在使用 plist 时遇到了麻烦。我有以下代码用于反射,我的应用程序中的模型对象:

struct Reflection {
let title: String
let body: String
let author: String
let favorite: Bool
let creationDate: Date
let id: UUID
}

extension Reflection {
var plistRepresentation: [String: AnyObject] {
    return [
        "title": title as AnyObject,
        "body": body as AnyObject,
        "author": author as AnyObject,
        "favorite": favorite as AnyObject,
        "creationDate": creationDate as AnyObject,
        "id": id as AnyObject
    ]
}

init(plist: [String: AnyObject]) {
    title = plist["title"] as! String
    body = plist["body"] as! String
    author = plist["author"] as! String
    favorite = plist["favorite"] as! Bool
    creationDate = plist["creationDate"] as! Date
    id = plist["id"] as! UUID
}
}

然后我有这个存储 Controller :

class StorageController {
fileprivate let documentsDirectoryURL = FileManager.default
    .urls(for: .documentDirectory, in: .userDomainMask)
    .first!

fileprivate var notesFileURL: URL {
    return documentsDirectoryURL
        .appendingPathComponent("Notes")
        .appendingPathExtension("plist")
}

func save(_ notes: [Reflection]) {
    let notesPlist = notes.map { $0.plistRepresentation } as NSArray
    notesPlist.write(to: notesFileURL, atomically: true)
}

func fetchNotes() -> [Reflection] {

    guard let notePlists = NSArray(contentsOf: notesFileURL) as? [[String: AnyObject]] else {
        print("No notes")
        return []
    }
    print("Notes found")
    return notePlists.map(Reflection.init(plist:))
}
}

当我调用 save() 并尝试写入 plist 时,我没有收到任何错误。但是,当我调用 fetchNotes() 时,它会打印“No Notes”,这意味着使用这些内容的数组为零或者无法转换为字典。为什么会这样?

最佳答案

UUID 不是属性列表的有效元素。您需要将其作为字符串存储在属性列表中,例如

“id”: id.uuidString as AnyObject

并将其转换回来,如下所示:

id = UUID(uuidString: plist[“id”] as! String)!

关于ios - 为什么这个 plist 读/写失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48910052/

相关文章:

cocoa - 可以从不受信任的来源安全地读取 plist 吗?

ios - CGColorRef 不透明类型的对象的 ID

ios - 是否可以在 nib 中使用 View Controller ?还是只是 UIViews?

swift - 为什么我的 UICollectionViewController 不显示任何内容?

ios - 创建一个通用函数,该函数接受 View Controller 类型作为参数,并根据该类型返回自定义 View Controller

ios - 在 iOS 上保存用户游戏分数

ios - 对 arc4random() 施加限制?

ios - 使用 Realm 或 UserDefaults 存储经过身份验证的用户数据?

objective-c - 如何在没有 Swift 参数的情况下调用 Objective-C `initFoo` 方法?

ios - Objective-C 访问 Plist 中的特定项目