经常在开发中将字典,JSON或者其他的数据类型转成模型,那模型的作用是什么呢? 为什么不直接将获取到的数据赋值给对应的显示控件呢?
答案是: 模型(专门存放数据的对象)其实就是一个用来存储和读取你网络请求获取到的数据的容器,用来存放和读取你的数据,数据模型,专门用来存放数据的对象,用它来表示数据会更加专业
模型设置数据和取出数据都是通过它的属性,属性名如果写错了,编译器会马上报错,因此,保证了数据的正确性
使用模型访问属性时,编译器会提供一系列的提示,提高编码效率
例子:
cell类中:
//cell中控件 contentlabel
var contentlabel:UILabel?
class CellModel{
var content;String = ""
//初始化方法
init(labelString: String){
self.content = labelString
}
}
func setCell(_ model: cellModel){
self.contentlabel.text = model.content
}
View中:
//假设网络请求获取到的数据为 getResponse(String类型)
let source:String = getResponse
//注意要转模型了
let model:CellModel = CellModel(content: "source")
let endModel = model
//对数组,元组,或者其他结构复杂的数据是同理,自己慢慢捋一捋