23

运行项目时,我在输出窗口中得到以下信息:

An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: connection.messageQueue
Observed object: <Client: 0x10011ddb0>
...

你明白了。问题是,我不知道为什么会这样。但是,似乎一切正常。这是导致问题的代码:

-(id) initWithIdentifier:(NSString*)ident andClient:(Client*)chatClient {
    if(![super initWithNibName:@"ChatView" bundle:nil]) {
        return nil;
    }
    [self setTitle: ident];
    client = chatClient;
    [self setIdentifier:ident];

    inContext = false;

    [client addObserver:self forKeyPath:@"connection.messageQueue" options:NSKeyValueObservingOptionNew context:NULL];
    return self;
}

-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSAttributedString* rar = [[NSAttributedString alloc] initWithString:@"test"];
    [[textView textStorage] appendAttributedString:rar];
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

我想我会展示与此相关的所有代码。该类只有几个方法,所以这就是您需要查看的全部内容。我什至没有使用更改,我只是在 KVO 事件被触发时进行“测试”。

由于消息一直在进来,堆栈跟踪变得非常快。然而,似乎一切正常。

有什么线索吗?

4

3 回答 3

50

[super observeValueForKeyPath:ofObject:change:context:]如果您处理通知,则不应致电。你应该只为你自己不处理的通知调用它。

于 2012-09-04T19:55:24.957 回答
16

我遇到了同样的问题:An -observeValueForKeyPath:ofObject:change:context: message was received but not processed。我在这里用谷歌搜索过,然后我自己想出来了,所以也许它可以帮助别人。

对我来说,问题是:注册为观察者的对象(如果您有... addObserver:self ...那么该对象就是self)在值更改时已被释放。但是观察者仍然被注册,所以-observeValueForKeyPath:ofObject:change:context:消息被nil观察者接收。

于 2013-01-17T08:01:47.777 回答
1

确保你只对你不感兴趣的东西调用 super。

class Layer: CALayer {
    
    private let key1 = "transport"
    private let key2 = "position"
        
    override init() {
        super.init()
        addObserver(self, forKeyPath: key1, options: [], context: nil)
        addObserver(self, forKeyPath: key2, options: [], context: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == key1 || keyPath == key2 {
            
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
    
    deinit {
        removeObserver(self, forKeyPath: key1)
        removeObserver(self, forKeyPath: key2)
    }
}
于 2021-06-03T07:37:41.010 回答