开发者

About key value observers in iPad

Hello i am very new to the iPad programing.Can any one explain me how to use key value observers in iPad.i need to check if a particular variable value is changed and based on that i trigger one method.One ap开发者_如何学编程proach is to use NSTimer to continuously check the variable value but i know this can be done better by using key value observers so please help me understand key value observers concept.Thanks in advance


Say you have declared a property @property (retain) NSNumber myNumber; in your interface.
Then you can observe value changes with KVO.

Observe changes (put this in your init method for example)

[self addObserver:self forKeyPath:@"myNumber" options:NSKeyValueObservingOptionNew context:nil];

Then implement the following method:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"myNumber"]) {
        // do stuff here
    }
}

And remove the observer in the dealloc method:

[self removeObserver:self forKeyPath:@"myNumber"];

You can refer to Key-Value Observing Programming Guide for further information.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜