【问题标题】:KVO not working! Not sure what to put in forKeyPath?KVO 不工作!不确定要在 forKeyPath 中添加什么?
【发布时间】: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的方法?

【问题讨论】:

标签: ios objective-c uikit


【解决方案1】:

而不是使用

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

使用

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

它将完美运行。

【讨论】:

    【解决方案2】:

    同时使用:

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

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2019-10-09
      相关资源
      最近更新 更多