gpt4 book ai didi

ios - 这个 observeValueForKeyPath 有什么问题 :ofObject:change:context: implementation?

转载 作者:技术小花猫 更新时间:2023-10-29 10:14:34 27 4
gpt4 key购买 nike

在我的 UIScrollView 子类中,我正在观察框架变化:

[self addObserver:self forKeyPath:@"frame" options:0 context:NULL];

我的observeValueForKeyPath:ofObject:change:context:实现如下:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == self && [keyPath isEqualToString:@"frame"]) {
[self adjustSizeAndScale];
}
if ([UIScrollView instancesRespondToSelector:@selector(observeValueForKeyPath:ofObject:change:context:)]) {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; // Exception
}
}

但是这段代码出现异常:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '<WLImageScrollView: 0x733a440; baseClass = UIScrollView; frame = (0 0; 320 416); clipsToBounds = YES; layer = <CALayer: 0x7346500>; contentOffset: {0, 0}>: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: frame
Observed object: <WLImageScrollView: 0x733a440; baseClass = UIScrollView; frame = (0 0; 320 416); clipsToBounds = YES; layer = <CALayer: 0x7346500>; contentOffset: {0, 0}>
Change: {
kind = 1;
}
Context: 0x0'

这是否意味着 UIScrollView 实现了 observeValueForKeyPath:ofObject:change:context: 但抛出上述异常?

如果是这样,我如何正确实现 observeValueForKeyPath:ofObject:change:context: 以便我既可以处理我感兴趣的更改,又可以让父类(super class)有机会处理它感兴趣的更改?

最佳答案

添加观察者时应添加一个context 值。在您的 -observeValueForKeyPath 方法中,检查上下文参数。如果它不是您在添加观察者时传递的上下文,那么您就知道此消息不是针对您的子类的,您可以安全地将它传递给父类(super class)。如果它相同的值,那么您知道它是为您准备的,您不应该将它传递给 super。

像这样:

static void *myContextPointer;

- (void)addSomeObserver {
[self addObserver:self forKeyPath:@"frame" options:0 context:&myContextPointer];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context != &myContextPointer) {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
else {
// This message is for me, do whatever I want with it.
}
}

关于ios - 这个 observeValueForKeyPath 有什么问题 :ofObject:change:context: implementation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6574714/

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