KVO:观察全局NSNumber

发布于 2024-12-20 20:23:07 字数 294 浏览 3 评论 0原文

我有静态全局 NSNumber 值,我需要观察它。如果它是某个对象的成员,我就不会有任何问题。但我该如何处理全局范围呢?我想我可以使用,

[globalVar addObserver:self forKeyPath:**integerValue** options:... ]

但这看起来很难看,因为我也可以使用“intValue”KeyPath,并且我需要观察 NSNumber,而不是它的 int 部分,即使它是我现在使用的唯一部分。让这个特定的变量成为某个类的一部分似乎不是一个“正确”的想法。谢谢!

I have static global NSNumber value and i need to observe it. If it was member of some object, i would have no problems whatsoever. But what do i do with global scope? I guess i could use

[globalVar addObserver:self forKeyPath:**integerValue** options:... ]

but that seems ugly because i might as well use "intValue" KeyPath and i need to observe NSNumber, not it's int part, even if it's the only part of it i''m using now. Making this particular variable part of some class doesn't seem like a "right" think to do. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

樱花细雨 2024-12-27 20:23:07

简单的回答:你不能。观察是一种软件机制,从根本上涉及方法调用,将存储(即机器指令)存储到全局变量中,不提供任何挂钩来挂起该机制。

最好的选择是重新考虑您的设计。考虑将值存储在单例类中并在那里访问/观察它。

硬答案:编写您自己的 NSNumber可变版本(其实例不可变)并让此类实现键值观察协议(这个类可能只是一个带有 NSNumber 实例变量的包装器)。现在将此类的实例存储在全局变量中,并向其中添加您喜欢的任何观察者。

Easy answer: you can't. Observing is a software mechanism which fundamentally involves method calls, doing a store (i.e. a machine instruction) into a global variable provides no hook to hang the mechanism on.

The best option is to re-think your design. Think of storing the value in a singleton class and accessing/observing it there.

Hard answer: write your own mutable version of NSNumber (an instance of which is immutable) and have this class implement the key-value observing protocol (this class might just be a wrapper with an NSNumber instance variable). Now store and instance of this class in your global variable and add any observers you like to it.

眼泪也成诗 2024-12-27 20:23:07

执行此类操作的通常方法是使其成为可从某些全局可用对象(例如 NSApp 或其委托)访问的值。

The usual way to do this kind of thing is by making it a value reachable from some globally-available object, such as NSApp, or its delegate.

上课铃就是安魂曲 2024-12-27 20:23:07

CRD 是对的,“在 KVO 中,仅观察到属性,而不是值”。通常,字典或自定义对象是 KVO,但不是叶子(值)本身(数字、字符串)。面对类似的问题,我最终扩展了 NSNumber 类,使其 符合 KVO
现在,如果您正在寻找不同的方法来在应用程序中实现通知,我强烈建议阅读 这篇文章

CRD is right, "In KVO only the property is observed, not the value" Typically dictionaries or custom objects are KVO but not the leaves (values) themselves (numbers, strings). Facing a similar problem, I finally extended the NSNumber class making it KVO compliant.
Now if you are looking for different approaches to achieve notifications in your app, I would strongly suggest to read this article.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文