您将必须像这样将History Model类制作为NSCoding
迅捷4和5。
class SSGIFHistoryModel: NSObject, NSCoding {
var bg_image: String
var total_like: String
var total_view: String
let gifID: String
var title: String
init(bg_image: String, total_like: String, total_view: String, gifID: String, title: String) {
self.bg_image = bg_image
self.total_like = total_like
self.total_view = total_view
self.gifID = gifID
self.title = title
}
required init?(coder aDecoder: NSCoder) {
self.bg_image = aDecoder.decodeObject(forKey: "bg_image") as? String ?? ""
self.total_like = aDecoder.decodeObject(forKey: "total_like") as? String ?? ""
self.total_view = aDecoder.decodeObject(forKey: "total_view") as? String ?? ""
self.gifID = aDecoder.decodeObject(forKey: "gifID") as? String ?? ""
self.title = aDecoder.decodeObject(forKey: "title") as? String ?? ""
}
func encode(with aCoder: NSCoder) {
aCoder.encode(bg_image, forKey: "bg_image")
aCoder.encode(total_like, forKey: "total_like")
aCoder.encode(total_view, forKey: "total_view")
aCoder.encode(gifID, forKey: "gifID")
aCoder.encode(title, forKey: "title")
}
}
之后,您将需要将该对象归档到NSData中,然后将其保存为用户默认值,并从用户默认值中检索它,然后再次将其取消存档。您可以像这样存档和取消存档
func saveGIFHistory() {
var GIFHistoryArray: [SSGIFHistoryModel] = []
GIFHistoryArray.append(SSGIFHistoryModel(bg_image: imageData.bg_image, total_like: imageData.total_like, total_view: imageData.total_view, gifID: imageData.quote_id, title: imageData.title))
if let placesData = UserDefaults.standard.object(forKey: "GIFHistory") as? NSData {
if let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [SSGIFHistoryModel] {
for data in placesArray {
if data.gifID != imageData.quote_id {
GIFHistoryArray.append(data)
}
}
}
}
let placesData2 = NSKeyedArchiver.archivedData(withRootObject: GIFHistoryArray)
UserDefaults.standard.set(placesData2, forKey: "GIFHistory")
}
希望这能解决您的问题