我处理这个问题通过重写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];
}
}
请注意,如果您有子视图也观察模型,模型的变化在两道发生。首先,整个视图层次与旧模型断开。然后整个视图层次连接到新模型。
就这样我很清楚,您的VIEW具有自定义对象属性?我认为这会使编码比需要的更困难。通常你希望ViewController能够访问模型,并且IT更新视图 – Pinwheeler 2013-04-10 01:15:23
这是正确的。我是这样构建的,以便视图对它所描绘的模型有一个清晰的概念。也许最好让视图控制器在视图上分配这些属性。 – Ned 2013-04-10 01:38:23
MVC上有许多变种。观察观察模型中的变化并自行更新是许多常见风格之一。 – 2013-04-10 03:10:17