2016-01-07 44 views
1
#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController 

@property BOOL myBoolean; 
@end 

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 
@synthesize myBoolean; 
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
     myBoolean = false; 
    [self addObserver:self forKeyPath:@"myBoolean" options:NSKeyValueObservingOptionNew context:nil]; 
    myBoolean = true; 

} 
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ 
    if([keyPath isEqual:@"myBoolean"]){ 
     NSLog(@"changed detected"); 
    } 
} 

-(void)viewDidDisappear:(BOOL)animated{ 
    [self removeObserver:self forKeyPath:@"myBoolean"]; 
} 
- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end 

这里我试图用KVO做一个简单的值更改检查。我不知道要在forKeyPath中放置什么,所以我将变量名称设置为“myBoolean”。KVO不工作!不知道要在forKeyPath中放置什么?

我设置布尔值为false然后添加观察者,然后使布尔值为true。它不会给我的NSLog“改变检测”

什么是使用KVO的正确方法?

+0

我认为它的工作原理与伊娃的setter和getter方法。有关更多详细信息,请参阅此链接http://stackoverflow.com/questions/24969523/simple-kvo-example。 –

回答

0

而不是使用

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

使用

[self addObserver:self forKeyPath:@"myBoolean" options:NSKeyValueObservingOptionInitial context:nil]; 

这将很好地工作的。

0

同时使用:

[self addObserver:self forKeyPath:@"myBoolean" options: (NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial) context:nil]; 
相关问题