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];
}
}
モデルも監視するサブビューがある場合、モデルの変更は 2 つのパスで発生することに注意してください。まず、ビュー階層全体が古いモデルから切断されます。次に、ビュー階層全体が新しいモデルに接続されます。