我正在尝试做简单的KVO示例,但我遇到了问题。
这是我的* .m文件:
#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
注意:我有一个按钮,点击该按钮会增加number
属性。
我想在number
属性更改时收到通知。
代码无效,我无法理解为什么。
答案 0 :(得分:24)
KVO适用于setter和getter,incNumber
您正在直接访问iVar,而不是使用self.number
- (IBAction)incNumber:(id)sender
{
self.number++;
NSLog(@"%d", self.number);
}
答案 1 :(得分:9)
而不是:
_number++;
尝试:
[self willChangeValueForKey:@"number"];
_number++;
[self didChangeValueForKey:@"number"];
或者更好的只是:
self.number++
让系统处理willChangeValueForKey:
和didChangeValueForKey:
方法。
答案 2 :(得分:2)
@interface TraineeLocationCell : UIView
@property (strong, nonatomic) NSString *traineeAddress;
@end
@implementation
// in textview delgate method i am setting traineeAddress string value
- (void)textViewDidEndEditing:(UITextView *)textView
{
if (textView.text.length >0)
[self setValue:textView.text forKey:@"traineeAddress"];
}
@end
以及我正在使用此课程的其他课程
TraineeLocationCell *locationView;//create object here
[locationView addObserver:self forKeyPath:@"traineeAddress" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];//observing the key in this class
//这是代理方法,它处理的值是否改变
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"traineeAddress"]){
if (!settingsValues.address)
settingsValues.address = [[NSMutableArray alloc]initWithObjects:[change valueForKey:@"new"], nil];
else
[settingsValues.address replaceObjectAtIndex:0 withObject:[change valueForKey:@"new"]];
}
}