ios - 将值存储在结构中以便稍后获取

标签 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 是结构。然后将它们添加到 [Product] 类型的数组 productData123 中,如下所示...

self.productData123.append(theProduct1)

此外,在我的 didSelectRow 中,我将我的结构中的图像分配给另一个 View Controller 中的另一个数组,就像这样......

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

let myprodObj = productData123[indexPath.row]

controller.productImages12 = myprodObj.images

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

最佳答案

您可以为此使用 Core Data,但您可能希望首先考虑更轻量级的解决方案。如果您使用的是 Swift 4,则可以访问用于序列化对象的 Encodable/Decodable/Codable 协议(protocol)。

考虑以下几点:

如果您要在您的产品类上采用 Codable 协议(protocol),那么您可以将您的对象从您的 API 反序列化到文件系统(示例中的文档目录)。由于 UIImage 不符合 Codable 协议(protocol),您需要手动将解码/编码处理为另一种类型(下例中的 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

关于ios - 将值存储在结构中以便稍后获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47936806/

相关文章:

objective-c - NSOperation 内的 ASynchronous NSURLConnection 与 NSInvocation?

ios - 在后台线程中恢复 NSManagedObject 关系

iOS - scrollViewDidEndDecelerating 为 scrollView 和 collectionView 运行

ios - NSFetchedResultsController -sectionNameForKeypath 如何获取其数据?

ios - 覆盖本地化字符串的 NSManagedObject getter

ios - 如何最好地子类化 NSManagedObject 以提供一组核心方法

ios - 对 NSMutableDictionary 进行排序

ios - 如何确定 iOS 上的用户带宽

swift - SKAction 仅更新最后一个实例化的 Sprite

ios - 如何使用 Carthage 构建仅适用于 ARM* 架构的框架?