KVO不工作!不确定要放入forKeyPath的内容?

时间:2016-01-07 07:19:05

标签: ios objective-c uikit

#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。”

我将布尔值设置为false,然后添加观察者,然后使布尔值为true。它没有给我NSLog“检测到已更改”

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

2 个答案:

答案 0 :(得分:0)

而不是使用

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

使用

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

它会完美运作。

答案 1 :(得分:0)

同时使用:

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