I've got a UITableView.
Here I got different cell's. Each cell has a model. With KVO and NotificationCenter the cell listen to the model for changes. When I leave the ViewController I get this error:
An instance 0x109564200 of class Model was deallocated while key value observers were still registered with it.
Observation info was leaked, and may even become mistakenly attached to some other object.
Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info:
<NSKeyValueObservationInfo 0x109429cc0> (
<NSKeyValueObservance 0x109429c50: Observer: 0x10942d1c0, Key path: name, Options: <New: NO, Old: NO, Prior: NO> Context: 0x0, Property: 0x10968fa00>
)
In the cell I do this when the model property is set/changed:
[_model addObserver:self
forKeyPath:@"name"
options:0
context:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(modelIsInvalid:)
name:@"modelIsInvalid"
object:_model];
Then in the cell's dealloc:
- (void)dealloc
{
NSLog(@"DEALLOC CELL");
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_model removeObserver:self forKeyPath:@"name"];
}
In the model I also check when it get's deallocated:
- (void)dealloc
{
NSLog(@"DEALLOC MODEL");
}
All cell's are deallocated before all the models, but still I get this error. Also I'm not sure how to set the breakpoint mentioned in the error.
It won't work because the cells are being reused. So when the cell goes off the screen it's not deallocated, it goes to reuse pool.
You shouldn't register notifications and KVO in cell. You should do it in table view controller instead and when the model changes you should update model and reload visible cells.