【发布时间】:2016-01-07 07:19:05
【问题描述】:
#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”。
我在添加观察者之前将布尔值设置为假,然后将布尔值设置为真。它没有给我“检测到更改”的 NSLog
什么是正确使用KVO的方法?
【问题讨论】:
-
我认为它适用于 iVar 的 setter 和 getter 方法。有关详细信息,请参阅此链接stackoverflow.com/questions/24969523/simple-kvo-example。
标签: ios objective-c uikit