Cocoa 中的自动键值观察
随着我对 KVO 和 KVC 的了解越来越多,我变得很好奇 -
NSObject 在访问 setter 方法时如何提供自动 KVO?
如果我使用名为 setName 的访问器创建一个新对象,
时观察者如何得到通知?
当有人调用[obj setName:@"Mystery"];
感谢您的任何反馈
As I learn more about KVO and KVC, I have become curious -
How does NSObject provide automatic KVO when accessing setter methods?
If I create a new object with an accessor named setName,
how does an observer get notified when someon calls
[obj setName:@"Mystery"];
Thanks for any feedback
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我总是向人们解释“Cocoa 中没有什么魔法;它只是代码”。但 KVO 近乎神奇。这就是所谓的isa-swizzling。您的类会在运行时(第一次有人观察您时)转换为动态生成的子类,该子类会重载所有 getter 和 setter。对
-class
的调用会欺骗您并返回旧类,因此如果您直接查看isa
,除了在调试器中之外,您不会看到神奇的子类指针。注意到 KVO 一定很奇怪是 Cocoa 启蒙的重要一步。恭喜。
键值观察实现细节
I always explain to people that "nothing is magic in Cocoa; it's just code." But KVO borders on magic. It's called isa-swizzling. Your class is transformed at runtime (the first time anyone observes you) into a dynamically generated sub-class that overloads all getters and setters. Calls to
-class
are wired to lie to you and return the old class, so you won't see the magic subclasses except in the debugger if you look directly at theisa
pointer.Noticing that KVO must be bizarre is a major step in Cocoa enlightenment. Congratulations.
Key-Value Observing Implementation Details