我處理這個問題通過重寫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