我通过这样的覆盖来处理这个setModel:
问题:
- (void)setModel:(Model *)model {
if (model != _model) {
[self disconnectFromModel];
_model = model;
[self connectToModel];
}
}
dealloc
我也打电话给disconnect
:
- (void)dealloc {
[self disconnectFromModel];
}
在connect
中,我建立与模型的连接(如果有的话),并在适当的情况下将模型(或模型的某些部分)传递给我的子视图。例子:
- (void)connectToModel {
if (_model) {
// Maybe start KVO...
[_model addObserver:self forKeyPath:@"name"
options:NSKeyValueObservingOptionInitial context:&MyKVOContext];
// Or maybe register for notifications...
nameNotificationObserver = [[NSNotificationCenter defaultCenter]
addObserverForName:ModelNameDidChangeNotification object:_model queue:nil
usingBlock:^(NSNotification *note) {
[self modelNameDidChange];
}];
// Maybe pass part of the model down to a subview...
[self.addressView setModel:model.address];
}
}
在disconnect
中,我只是撤消我在 中所做的事情connect
:
- (void)disconnectFromModel {
if (_model) {
[_model removeObserver:self forKeyPath:@"name" context:&MyKVOContext];
[[NSNotificationCenter defaultCenter] removeObserver:nameNotificationObserver];
nameNotificationObserver = nil;
[self.addressView setModel:nil];
}
}
请注意,如果您确实有也观察模型的子视图,则模型的更改发生在两次传递中。首先,整个视图层次结构与旧模型断开连接。然后整个视图层次结构连接到新模型。