我正在尝试将类项目的集合保存到json文件中。因此,当我重新编写它时,我想做到尽可能完美,包括最先进的技术和尽可能独立的输入。
这是我的(轻松)方法: 首先,我使用一个循环,将所有数据从类项目复制到名为“ CacheSave”的结构数组中。然后,我定义了对我的结构的扩展。
// MARK: - The protocol, when implemented by a structure makes the structure archive-able
protocol Dictionariable {
func dictionaryRepresentation() -> NSDictionary
init?(dictionaryRepresentation: NSDictionary?)
}
// MARK: - Implementation of the Dictionariable protocol by CacheSave struct
extension CacheSave: Dictionariable {
func dictionaryRepresentation() -> NSDictionary {
let representation: [String: AnyObject] = [
"fullpath": fullpath as AnyObject,
...
"labelColors": labelColors as AnyObject
]
return representation as NSDictionary
}
init?(dictionaryRepresentation: NSDictionary?) {
guard let values = dictionaryRepresentation else {return nil}
if let fullpath = values["fullpath"] as? String,
...
let labelColors = values["labelColors"] as? UInt16
{
self.fullpath = fullpath
...
self.labelColors = labelColors
} else {
return nil
}
}
}
// MARK: - Methods adding in archiving and unarchiving the structures
// Single Structure Instances
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())
}
// Multiple Structure Instances
func extractStructuresFromArchive<T: Dictionariable>() -> [T] {
guard let encodedArray = NSKeyedUnarchiver.unarchiveObject(withFile: path()) as? [AnyObject] else { return [] }
return encodedArray.map{$0 as? NSDictionary}.compactMap{T(dictionaryRepresentation: $0)}
}
func archiveStructureInstances<T: Dictionariable>(structures: [T]) {
let encodedValues = structures.map{$0.dictionaryRepresentation()}
NSKeyedArchiver.archiveRootObject(encodedValues, toFile: path())
}
// ----- end saving -----
我可以保存文件,很好。但是,当尝试使用
再次加载文件时self.cacheData = extractStructuresFromArchive()
我总是零。有想法吗?
我知道,此实现不使用json格式。因此,下一步(当它可以正常工作时)我想使用json。
我的问题是:当我们牢记自己是否已经有了Swift 4.2,并对其库进行了更多扩展时,是否有一种简单的方法来完成所有这些工作?网上的所有答案仅涵盖了这种方法的一个方面,并且可能由于库的改进而过时了。
有任何提示吗?