addObserverでのデータ同期取得
データの更新タイミングを取得する方法はないものかと探していたら、addObserverがそれだった。
使い方は、更新の監視をしたいオブジェクトに対してaddObserver:forKeyPath:options:contextを張る。キー値を所有するオブジェクト、つまりNSDictionaryやNSUserDefaultsなどを対象にすることができる。更新通知はobserveValueForKeyPathにて処理される。
- addObserver
- 更新先
- forKeyPath
- 状態を取得する値のキー値
- options
- 状態がどのように変わったときに伝えるか
- context
- オプション(用途不明)
forKeyPathの指す意味がよくわからなくて、NSArrayとかを指定してしまっていてはまった。
- (IBAction)showPicker:(id)sender { pickerBase = [[[ColorPickerController alloc] initWithNibName:@"ColorPicker" bundle:nil] retain]; pickerBase->colorType = [[NSMutableDictionary dictionary] retain]; [pickerBase->colorType addObserver:self forKeyPath:@"ColorValue" options:NSKeyValueObservingOptionNew context:nil]; [self presentModalViewController:pickerBase animated:YES]; } -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { [show setTitle:(NSString *)[pickerBase->colorType objectForKey:@"ColorValue"] forState:UIControlStateNormal]; }