我正在关注iOS教程,并且我遇到了问题。我有这个代码用于反射,我的应用程序中的模型对象:
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
}
}
然后我有这个存储控制器:
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",暗示使用这些内容的数组为nil或者无法将其强制转换为字典。为什么会这样?
答案 0 :(得分:3)
UUID
不是属性列表的有效元素。您需要将其作为字符串存储在属性列表中,例如
“id”: id.uuidString as AnyObject
并将其转换回来:
id = UUID(uuidString: plist[“id”] as! String)!