简单的KVO例子 [英] Simple KVO example
本文介绍了简单的KVO例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试做一个简单的KVO示例,但我遇到了问题。
I am trying to do simple KVO example, but I am having problems.
这是我的* .m文件:
This is my *.m file:
#import "KVO_ViewController.h"
@interface KVO_ViewController ()
@property NSUInteger number;
@end
@implementation KVO_ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self addObserver:self forKeyPath:@"number" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)incNumber:(id)sender
{
_number++;
NSLog(@"%d", _number);
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"From KVO");
if([keyPath isEqualToString:@"number"])
{
id oldC = [change objectForKey:NSKeyValueChangeOldKey];
id newC = [change objectForKey:NSKeyValueChangeNewKey];
NSLog(@"%@ %@", oldC, newC);
}
}
@end
注意:我有一个按钮,点击它会增加数字
属性。
我希望在<$时收到通知c $ c> number 属性已更改。
Note: I have a button which when clicked it will increment the number
property.
I want to be notified when number
property is changed.
代码无效,我无法理解为什么。
The code is not working and I can not figure it why.
推荐答案
KVO适用于setter和getter,而 incNumber
你是直接的访问iVar而不是使用 self.number
KVO works with setter and getter and in incNumber
you are directly accessing iVar so instead of that use self.number
- (IBAction)incNumber:(id)sender
{
self.number++;
NSLog(@"%d", self.number);
}
这篇关于简单的KVO例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文