I'm very beginner in iOS development, so this problem may look trivial. I searched and could not find any questions about this problem. But I wonder what is correct approach of updating custom cells of a UITableView
when you change your data model at run time after initial loading of cells from data model. From change, I mean data entry change, not adding or removing data.
Here is an example. Let's say that I have these DataModel
and DataModelCell
as follows:
class DataModelView : UITableViewCell {
@IBOutlet weak var mainLabel: UILabel!
}
class DataModel {
var title: String = "" {
didSet {
// which cell this entry is connected to?
}
}
}
...
items: [DataModel] = []
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DataModelView", for: indexPath)
cell.mainLabel?.text = items[indexPath.item].title
// addition line for each approach
// approach 1:
// items[indexPath.item].view = cell
// approach 2:
// items[indexPath.item].viewIndexPath = indexPath
return cell
}
My problem is that when I changed title
of one of cells in my data model at run time, I like to update corresponding cell in UI. I like to know what is the best approach to make a relationship between data model'd entry and cell in UITableView
.
There are 3 different approaches that comes to my mind. I want to know if they are correct or not or if there is any better method:
1st approach: a weak
pointer to cell in my data entry like this:
class DataModel {
weak var view: DataModelView?
var title: String = "" {
didSet {
view?.mainLabel?.text = title
}
}
}
2nd approach: keep IndexPath
of cell in my data entry like this:
class DataModel {
var viewIndexPath: IndexPath?
var title: String = "" {
didSet {
// call delegate to controller and ask to update cell for viewIndexPath
}
}
}
3rd approach: don't keep anything which corresponds to cell in data entry:
class DataModel {
var title: String = "" {
didSet {
// call delegate to controller and ask to find and update cell for self
}
}
}
In first 2 approaches, I keep relationship between cell and data model in my data model. In 3rd approach, I need to keep this relationship in controller.
Are all these approaches correct(especially first one)? Which one do you suggest? and What is best approach generally?
I have seen that people keep a pointer to data model in their view in order to update data model from view. I wonder if it is correct in the other way too or not(1st approach).