Do I need to subscribe/unsubscribe to individual elements of an array?
I want to update each table view cell individually to reflect changes in the backing array. By changes I mean not append/remove operations but update of the properties of the objects of the array. I hope I was able to explain what I want to achieve. Thanks
To use KVO, declare the model object with
dynamic
properties:Then, let the cell process the KVO. First, I'd have a protocol by which the cell can inform the table view that it needs to be reloaded:
And the table view controller can conform to this
CustomCellDelegate
protocol and reload the cell when informed it needs to:So, and then define cell to setup and handle KVO. In Swift 4 and iOS 11, you can use the closure-based
observe
method with the new strongly typed keys:In Swift 3:
And now the
cellForRowAtIndexPath
can just set thedelegate
andobject
properties:In my opinion, this KVO mechanism is better than the Swift observer mechanism because the model object doesn't need to know (nor should it) anything about the observer. It just needs to indicate that it supports dynamic dispatch, and that's it.
For Swift 2 rendition of the above, see previous revision of this answer.
You could use setter observer on stored variables in the backing array.
when you change the value in
array
the willSet and didSet is executed, and you can call a function on the cell doing the update you want.You could use a delegate to handle communication between the individual cell:s data (say, elements of your array) and the owner of these cells (i.e., owner of the array). Changes in the "backing array" can be propagated to the array owned using delegate callbacks with appropriate information.
E.g.:
Example usage: