gpt4 book ai didi

objective-c - 为什么此代码不符合 KVO 标准?

转载 作者:行者123 更新时间:2023-12-03 17:32:11 24 4
gpt4 key购买 nike

我有一个 NSViewController 子类,它有一个方便的方法来返回这样的窗口 Controller

@interface ILViewController : NSViewController

- (ILWindowController *)windowController;

@end

@implementation ILViewController

- (NSWindowController *)windowController {
return self.view.window.windowController;
}

- (void)setView:(NSView *)view {
[self willChangeValueForKey:@"windowController"];
[super setView:view];
[self didChangeValueForKey:@"windowController"];
}

@end

窗口 Controller 有一个名为 mainStatusNSString * 属性,我试图通过 View Controller 绑定(bind)到该属性。但是,我在运行时收到此错误。

Cannot update for observer <NSAutounbinderObservance 0x1005cf990> for the key path 
"windowController.mainStatus" from <ILViewController 0x1001976b0>, most likely because
the value for the key "windowController" has changed without an appropriate KVO
notification being sent. Check the KVO-compliance of the ILViewController class.

为什么会发生这种情况?我已正确发送 KVO 通知。

以下代码使用 ivar 并且实际上不符合 KVO 标准,结果不会导致任何错误......

@interface ILViewController : NSViewController {
ILWindowController *_windowController;
}

- (ILWindowController *)windowController;

@end

@implementation ILViewController

- (NSWindowController *)windowController {
return _windowController;
}

- (void)setView:(NSView *)view {
[super setView:view];
_windowController = view.window.windowController;
}

@end

这让我很困惑...有人能明白为什么第一个实现不符合 KVO 吗?

编辑

明白了,如果在为 ViewController 设置 View 后将 View 添加到窗口,那么 View 的窗口确实会在没有适当的 KVO 通知的情况下更改。但是,当我尝试观察 View 窗口的窗口 Controller 时,我收到这样的错误

KVO autonotifying only supports -set<Key>: methods that return void. Autonotifying 
will not be done for invocations of -[NSView _setWindow:].
Cannot remove an observer <NSKeyValueObservance 0x102e17880> for the key path
"window.windowController.mainStatus" from <NSView 0x102e13ec0>, most likely because
the value for the key "window" has changed without an appropriate KVO notification
being sent. Check the KVO-compliance of the NSView class.

因此,如果您无法观察 View 的窗口,那么当 View 的窗口发生更改时,肯定有某种方式可以收到通知。有谁知道怎么做吗?

此外,这些仍然不能解释为什么使用 iVar 且没有 KVO 通知的代码的第二个版本实际上可以工作。

最佳答案

如果您设置 View ,然后将 View 添加到窗口,则 windowController 将发生更改,而不会发送 KVO 通知。您需要观察自己的 View 的 window 并在发生变化时发出 will/did 更改通知(自动关键路径依赖的东西可能会为您执行此操作,我不记得它是否确实适用于路径或只是值)。同样,如果窗口的 windowController 发生变化,那么您也会遇到同样的问题。

编辑:该方法称为-automaticallyNotizesObserversForKey:。我倾向于说它不支持关键路径,因此您必须手动观察/通知自己。

关于objective-c - 为什么此代码不符合 KVO 标准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8829942/

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