将值存储在struct中以便稍后获取

时间:2017-12-22 06:26:54

标签: ios swift core-data struct

我从api获得了一些值,并将这些值添加到结构中,如下所示。

 let theProduct1 = Product(name: name, id: id, theRate: rate, quantity: qty, sku: skuCode, prdCateg: prodCat, prodDescr: description, images: myproductImages, mrp: mrp)

这里Product是结构。然后将这些添加到productData123类型的数组[Product]中,如下所示......

self.productData123.append(theProduct1)

此外,在我的didSelectRow中,我将结构中的图像分配给另一个视图控制器中的另一个数组,如此...

let controller = storyboard.instantiateViewController(withIdentifier: "catalogueIdentifier") as! CatalogueViewController

let myprodObj = productData123[indexPath.row]

controller.productImages12 = myprodObj.images

但问题是我想将productData123存储在CoreData / UserDefaults中,这样我就不需要每次都拨打api电话了。可以从数据库中获取所需的数据。

1 个答案:

答案 0 :(得分:1)

您可以使用Core Data,但您可能需要先考虑更轻量级的解决方案。如果您使用的是Swift 4,则可以访问Encodable / Decodable / Codable协议来序列化对象。

请考虑以下事项:

如果您要在产品类上采用Codable协议,则可以将对象从API序列化/序列化到文件系统(示例中的文档目录)。由于UIImage不符合Codable协议,因此您需要手动将解码/编码处理为另一种类型(下例中的Data)。

struct Product: Codable {
    var id: String?
    var name: String?
    var rate: Double?
    var quantity: Int?
    var sku: String?
    var productCatalog: String?
    var productDescription: String?
    var images: [UIImage] = []
    var mrp: String?

    private enum CodingKeys: String, CodingKey {
        case id
        case name
        case rate
        case quantity
        case sku
        case productCatalog
        case productDescription
        case images
        case mrp
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        self.id = try container.decode(String.self, forKey: .id)
        self.name = try container.decode(String.self, forKey: .name)
        self.rate = try container.decode(Double.self, forKey: .rate)
        self.quantity = try container.decode(Int.self, forKey: .quantity)
        self.sku = try container.decode(String.self, forKey: .sku)
        self.productCatalog = try container.decode(String.self, forKey: .productCatalog)
        self.productDescription = try container.decode(String.self, forKey: .productDescription)
        self.mrp = try container.decode(String.self, forKey: .mrp)

        if let imageData = try container.decodeIfPresent([Data].self, forKey: .images) {
            imageData.forEach({ (data) in
                if let image = UIImage(data: data) {
                    self.images.append(image)
                }
            })
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encodeIfPresent(id, forKey: .id)
        try container.encodeIfPresent(name, forKey: .name)
        try container.encodeIfPresent(rate, forKey: .rate)
        try container.encodeIfPresent(quantity, forKey: .quantity)
        try container.encodeIfPresent(sku, forKey: .sku)
        try container.encodeIfPresent(productCatalog, forKey: .productCatalog)
        try container.encodeIfPresent(productDescription, forKey: .productDescription)
        try container.encodeIfPresent(mrp, forKey: .mrp)

        var imageData = [Data]()
        for image in images {
            if let data = UIImagePNGRepresentation(image) {
                imageData.append(data)
            }
        }

        try container.encode(imageData, forKey: .images)
    }
}

然后,您可以使用JSON或PLIST编码器将该数据读写到磁盘:

struct ProductData {
    var products: [Product] = []

    var productsURL: URL {
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        guard let url = urls.first else {
            fatalError("Document Directory url invalid")
        }

        return url.appendingPathComponent("products.json")
    }

    mutating func loadProducts() {
        products.removeAll()

        guard let data = FileManager.default.contents(atPath: productsURL.path) else {
            return
        }

        let decoder = JSONDecoder()

        do {
            products = try decoder.decode([Product].self, from: data)
        } catch {
            // Handle Error
        }
    }

    mutating func saveProducts() {
        let encoder = JSONEncoder()

        let data: Data
        do {
            data = try encoder.encode(products)
        } catch {
            // Handle Error
            return
        }

        do {
            try data.write(to: productsURL)
        } catch {
            // Handle Error
        }
    }
}

有关自定义类型编码和解码的更多信息,请访问:Encoding and Decoding Custom Types