【问题标题】:Adding KVO Notification to property of same object将 KVO 通知添加到同一对象的属性
【发布时间】:2014-07-16 04:04:57
【问题描述】:

我想将 KVO 通知添加到控制器的属性之一,以便每当该属性发生更改时,observeValueForKeyPath 方法都会在同一个控制器中调用。这就是我想要做的做:

@interface ViewController ()

@property(strong, nonatomic)NSString *currentState;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _currentState = @"Active";
    [self addObserver:self forKeyPath:@"currentState" options:NSKeyValueObservingOptionNew context:NULL];
}


-(IBAction)changeState:(UIButton *)sender{
    if([_currentState isEqualToString:@"Active"])
        _currentState = @"Inactive";
    else
        _currentState = @"Active";
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if([keyPath isEqualToString: @"currentState"]) {
        NSLog(@"State Changed : %@",_currentState);
    }

但是这个方法 observeValueForKeyPath 在按钮点击时根本没有被调用。我搜索了更多关于它的示例,但它们都使用了两个不同类的对象来演示它。 我的问题是:

  1. 能否以我尝试的方式使用 KVO 通知,即在同一对象上使用?
  2. 如果是,上面的代码有什么问题?

任何帮助将不胜感激。

【问题讨论】:

  • 为什么不直接覆盖该属性的 getter 和 setter 并以这种方式捕获更改?
  • @rckoenes :是的,这也可以解决它。谢谢。

标签: objective-c ios7 key-value-observing


【解决方案1】:

通知没有触发,因为你直接修改了实例变量, 而不是使用属性访问器方法:

-(IBAction)changeState:(UIButton *)sender{
    if([self.currentState isEqualToString:@"Active"])
        self.currentState = @"Inactive";
    else
        self.currentState = @"Active";
}

【讨论】:

  • 别忘了删除 dealloc 中的观察者!
  • 非常感谢马丁。这就是问题所在。当然我会放一个dealloc。
猜你喜欢
  • 1970-01-01
  • 2012-01-10
  • 2015-11-15
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 2015-09-04
  • 2021-03-22
相关资源
最近更新 更多