【问题标题】:iOS - Choosing Model ClassiOS - 选择模型类
【发布时间】:2020-06-17 16:09:26
【问题描述】:

我可以使用相同的模型类来存储具有相同键的多种类型字典数组的数组数据吗?

例如,假设我有一个名为 ProductDetail 的模型类,用于存储带有键 ID、名称和图像的产品详细信息,并在 UITableViewController 中显示它们。

现在我有一个名为 categories 的不同类,具有相同的上述键。

这是我的模型类:

class TrendingProductsData: NSObject {

    var id : Int! = 0
    var name : String! = ""
    var image : String! = ""

}

我的问题是我可以使用 ProductDetail 模型来存储类别数据吗?

【问题讨论】:

    标签: ios objective-c swift


    【解决方案1】:

    如何为通用属性使用超级模型并扩展您拥有的属性。这就是我的意思:

    
    class BaseModel: NSObject {
    
        var id : Int = 0
        var name : String = ""
        var image : String = ""
    
        func setData(data: Any) {
            // Parse id, name and image from data
        }
    }
    
    class ProductDetail: BaseModel {
        // Add your other properties and/or functions
        var productProvider: String = "" // I added this to be an example
    
        override func setData(data: Any) {
            super.setData(data: data) // Since the key-value pairs are the same id, name and image will be parsed at BaseModel
    
            // Parse extra values such as  productProvider
        }
    }
    
    class Categories: BaseModel {
        // Add your other properties and/or functions
        var categorySubtitle: String = "" // I added this to be an example
    
        override func setData(data: Any) {
            super.setData(data: data) // Since the key-value pairs are the same id, name and image will be parsed at BaseModel
    
            // Parse extra values such as categorySubtitle
        }
    }
    
    

    通过这种方式,您可以创建具有公共属性的ProductDetailCategories 模型,如果需要,您可以添加单独的属性和函数。

    【讨论】:

      【解决方案2】:

      如果您想要更复杂的结构,例如 subCategory 等,它可能是一种更好的方式。但我认为基本上这些课程是你想要的。

      只有当 isCategory 为 false 时,产品才能有详细信息。

      class Product {
      
          var id : Int = 0
          var name : String = ""
          var image : String = ""
          var isCategory: Bool = false
      
          var productDetail: ProductDetail? = nil
      
      }
      
      class ProductDetail {
          var description : String = ""
          var price : Decimal?
      }
      

      【讨论】:

        猜你喜欢
        • 2016-07-04
        • 2014-12-04
        • 2018-08-23
        • 2018-10-25
        • 2021-07-09
        • 2016-01-07
        • 2016-05-31
        • 1970-01-01
        • 2017-03-22
        相关资源
        最近更新 更多