Swift 3 - 编码&解码结构对象数组

时间:2016-11-16 03:59:49

标签: arrays swift struct encode archive

我的模型是基于结构而不是类。因此,我遇到了一些麻烦,想知道如何编码/解码这些模型对象的数组。我试图按照建议在结构扩展中添加一个类。

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给了我一个"实例与值类型"的错误当我试图保存stocksArray时。对此问题的任何建议?

0 个答案:

没有答案