gpt4 book ai didi

ios - KVO observeValueForKeyPath 方法被调用了两次

转载 作者:行者123 更新时间:2023-11-28 21:44:24 47 4
gpt4 key购买 nike

我写了一个演示想尝试 KVO 编程,我找到了 observeValueForKeyPath当我只更改一次值时,方法总是执行两次,怎么了?请帮助我,谢谢

代码

状态同步器.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

最佳答案

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

你会检查其他 Controller 继承,它可能会扩展 ViewController

关于ios - KVO observeValueForKeyPath 方法被调用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30837149/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com