【问题标题】:Store values in struct to fetch it later将值存储在结构中以便稍后获取
【发布时间】:2017-12-22 06:26:53
【问题描述】:

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

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

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

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 并且可以从数据库中获取所需的数据。

【问题讨论】:

  • 如何从自己的(结构)模型跳转到 CoreData?
  • 实际上..这是一个建议..:) 但我最终想以某种方式存储我的productData123,以便以后可以获取它...
  • 如果您的目标是将数据保存到文件中,您可能希望使用 Class 而不是 Struct 创建模型。
  • 但是几乎所有的东西都已经实现了......此时更改为 Class 并不实际......:(我不能以任何方式存储我的结构......吗?
  • 然后运行搜索结构并保存。有些人已经展示了如何将结构模型保存到磁盘。

标签: ios swift core-data struct


【解决方案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

【讨论】:

    猜你喜欢
    • 2010-10-25
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 2020-09-08
    • 2021-10-04
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    相关资源
    最近更新 更多