プロパティ変更通知

objective-c 初めて触ってて変数変更に詰まったので備忘録

プロパティの変更の通知があれば対処できる処理だったので以下で対応

- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

  NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];  // 取得

  [ud addObserver:self forKeyPath:@”test” options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:NULL];

}

- (void)observeValueForKeyPath:(NSString *)keyPath

                      ofObject:(id)object

                      change:(NSDictionary *)change

                      context:(void *)context{

  if ([keyPath isEqualToString:@”test”]) {

//処理

}

}

keyPathで処理を分岐させる

UserDefaults に格納

他のやり方としてはプロトコル、カテゴリの使用ができる

おそらくそちらのほうが綺麗な処理になるんだろうけど、今の所これで問題ない。とりあえず動くの域を出ないので参考にする時は慎重に

多用すると if 以降がわかりづらくなりそう