KVO observeValueForKeyPath方法调用两次

时间:2015-06-15 03:58:48

标签: ios

我写了一个想要尝试KVO编程的演示,我找到了observeValueForKeyPath 当我只改变一次值时,方法总是执行两次,这有什么问题?请帮助我,谢谢

StatusSyncer.h

#import <Foundation/Foundation.h>

 @interface StatusSyncer : NSObject
 @property NSString *title;
 +(instancetype)sharedInstance;
@end

StatusSyncer.m

#import "StatusSyncer.h"
@implementation StatusSyncer
+ (instancetype)sharedInstance {
   static id _sharedInstance = nil;
   static dispatch_once_t oncePredicate;
   dispatch_once(&oncePredicate, ^{
      _sharedInstance = [[self alloc] init];
   });
   return _sharedInstance;
}
@end

ViewController.m

- (void)viewDidLoad {
   [super viewDidLoad];
   [self.statusSyncer addObserver:self forKeyPath:@"title"    options:NSKeyValueObservingOptionNew context:nil];

 }

 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"title"]) {
        NSLog(@"chane");
    }
}

-(StatusSyncer *)statusSyncer{
    if (_statusSyncer==nil) {
        _statusSyncer = [StatusSyncer sharedInstance];
    }

    return _statusSyncer;
}

DetailViewController.m

- (IBAction)changeAction:(id)sender {
    self.statusSyncer.title= @"newTitle叶";

}

-(StatusSyncer *)statusSyncer{
    if (_statusSyncer==nil) {
        _statusSyncer = [StatusSyncer sharedInstance];
    }

    return _statusSyncer;
}

输出:

2015-06-15 12:58:49.849 KVOAdvence[2433:74541] chane
2015-06-15 12:58:49.850 KVOAdvence[2433:74541] chane

2 个答案:

答案 0 :(得分:1)

OOOh,我犯了一个愚蠢的错误 DetailViewController超类是ViewController,这使得StatusSyncer添加 两次Observer

答案 1 :(得分:1)

我认为方法 addObserver:执行两次。

您将检查其他控制器继承,它可以扩展 ViewController