My model is built on a struct instead of a class. Because of that, I ran into some trouble of figuring how to encode/decode an array of these model objects. I tried to add a class to the struct extension as suggested.
import UIKit
import Foundation
enum Path: String { case Stock = "Stock" }
struct Stock {
var companyName: String?
var symbol: String?
var price: Double?
func documentsDirectory() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentDirectory = paths[0] as NSString return documentDirectory
}
func saveStocksArray() -> Bool {
let stockObjects = StockClass(stock: self)
let file = documentsDirectory().appendingPathComponent(Path.Stock.rawValue)
return NSKeyedArchiver.archiveRootObject(stockObjects, toFile: file)
}
func loadStocksArray() -> [Stock]? {
let file = documentsDirectory().appendingPathComponent(Path.Stock.rawValue)
let result = NSKeyedUnarchiver.unarchiveObject(withFile: file) return result as? [Stock]
}
}
extension Stock {
class StockClass: NSObject, NSCoding {
var stock: Stock? init(stock: Stock) {
self.stock = stock super.init() }
required init?(coder aDecoder: NSCoder) {
guard let companyName = aDecoder.decodeObject(forKey: "companyName") as? String else { stock = nil; super.init(); return nil }
guard let symbol = aDecoder.decodeObject(forKey: "symbol") as? String else { stock = nil; super.init(); return nil }
guard let price = aDecoder.decodeObject(forKey: "price") as? Double else { stock = nil; super.init(); return nil }
stock = Stock(companyName: companyName, symbol: symbol, price: price) super.init() }
func encode(with aCoder: NSCoder) {
if let stock = stock {
aCoder.encode(stock.companyName, forKey: "companyName")
aCoder.encode(stock.symbol, forKey: "symbol")
aCoder.encode(stock.price, forKey: "price")
}
}
}
}
let stocksArray = [Stock(companyName: "Tesla", symbol: "TSLA", price: 200.01), Stock(companyName: "Apple", symbol: "AAPL", price: 120.12)]Playground gave me an error of "instance vs value type" when I tried to save & load stocksArray. Any suggestion for this problem?