iOS-选择模型类
我可以使用相同的模型类来存储具有相同键的字典的多类型数组的数组数据吗 例如,我有一个名为ProductDetail的模型类,用于存储带有键id、名称和图像的产品详细信息,并在UITableViewController中显示它们 现在我有了一个名为categories的不同类,它具有上述相同的键 这是我的模型课:iOS-选择模型类,ios,objective-c,swift,Ios,Objective C,Swift,我可以使用相同的模型类来存储具有相同键的字典的多类型数组的数组数据吗 例如,我有一个名为ProductDetail的模型类,用于存储带有键id、名称和图像的产品详细信息,并在UITableViewController中显示它们 现在我有了一个名为categories的不同类,它具有上述相同的键 这是我的模型课: class TrendingProductsData: NSObject { var id : Int! = 0 var name : String! = ""
class TrendingProductsData: NSObject {
var id : Int! = 0
var name : String! = ""
var image : String! = ""
}
我的问题是,我是否可以使用ProductDetail模型来存储类别数据?如何使用通用属性的超级模型并扩展现有属性。我的意思是:
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
}
}
通过这种方式,您可以创建具有通用属性的
ProductDetail
和Categories
模型,如果需要,您可以添加单独的属性和函数 如果您想创建更复杂的结构,如子类别等,可以采用更好的方式。但我认为基本上这些课程就是你想要的
只有当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?
}