我正在尝试保存我的struct数组。我读了我能找到的关于这个主题的所有帖子。最后,我使用了一个示例并将其剥离了一点,但它不起作用。它没有保存,因此无法回读:
func path() -> String {
return URL(fileURLWithPath: "/Volumes/MacOS/fasttemp/Test.TXT").absoluteString
}
struct Movie {
let name: String
let releaseYear: Int
}
protocol Dictionariable {
func dictionaryRepresentation() -> NSDictionary
init?(dictionaryRepresentation: NSDictionary?)
}
extension Movie: Dictionariable {
func dictionaryRepresentation() -> NSDictionary {
let representation: [String: AnyObject] = [
"name": name as AnyObject,
"releaseYear": releaseYear as AnyObject
]
return representation as NSDictionary
}
init?(dictionaryRepresentation: NSDictionary?) {
guard let values = dictionaryRepresentation else {return nil}
if let name = values["name"] as? String,
let releaseYear = values["releaseYear"] as? Int {
self.name = name
self.releaseYear = releaseYear
} else {
return nil
}
}
}
func extractStructureFromArchive<T: Dictionariable>() -> T? {
guard let encodedDict = NSKeyedUnarchiver.unarchiveObject(withFile: path()) as? NSDictionary else {return nil}
return T(dictionaryRepresentation: encodedDict)
}
func archiveStructure<T: Dictionariable>(structure: T) {
let encodedValue = structure.dictionaryRepresentation()
NSKeyedArchiver.archiveRootObject(encodedValue, toFile: path())
}
func extractStructuresFromArchive<T: Dictionariable>() -> [T] {
guard let encodedArray = NSKeyedUnarchiver.unarchiveObject(withFile: path()) as? [AnyObject] else {return []}
return encodedArray.map{$0 as? NSDictionary}.flatMap{T(dictionaryRepresentation: $0)}
}
func archiveStructureInstances<T: Dictionariable>(structures: [T]) {
let encodedValues = structures.map{$0.dictionaryRepresentation()}
NSKeyedArchiver.archiveRootObject(encodedValues, toFile: path())
}
let movies = [
Movie(name: "Avatar", releaseYear: 2009),
Movie(name: "The Dark Knight", releaseYear: 2008)
]
// this fails!
archiveStructureInstances(structures: movies)
let someArray: [Movie] = extractStructuresFromArchive()
print("\(someArray[0].name)")
没有创建文件。该文件夹存在。它出什么问题了? 我正在使用XCode 8.2.1和Swift 3。
补充:我从另一个问题/答案中提取了这个例子。我还将它从3个减少到2个结构成员。我为Swift 3更新了它。但它仍然不起作用!这就是我要问的原因。
答案 0 :(得分:1)
您的path
错了。您不归档到文件。你必须使用一个目录。
将path()
方法更改为此from this answer):
func path() -> String {
let documentsPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
let path = documentsPath! + "/Movie"
return path
}
您的代码按预期打印Avatar
。