使用 NSArray 观察键值

发布于 2024-09-14 21:57:16 字数 437 浏览 0 评论 0原文

我查看了 SO 使用键值观察与 NSArray (或 NSMutableArray) 的示例,显然你需要使用 NSArrayController (这与我不熟悉的 KVO 不同),但我还没有找到如何做到这一点的具体示例。任何人都可以用一些示例代码来解释吗?

例如,如果我有一个 GameModel,它用 NSStringsNSArray (playerNameArray) 表示其玩家名称。我想观察这些字符串(视图控制器观察模型的数据)以更新视图中的各种内容。

如何收到玩家姓名数组已更改的通知?

编辑:iOS SDK是否支持NSArrayController?如果没有,还有其他办法吗?

I've looked on SO for examples of using Key Value Observing with an NSArray (or NSMutableArray) and apparently you need to use an NSArrayController (which unlike KVO I'm not familiar with), but I haven't found concrete examples of how to do this. Can anyone explain with some sample code?

For instance, if I have a GameModel which represents its player names with an NSArray (playerNameArray) of NSStrings. I want to observe those strings (the view controller observes the model's data) to update various things in the view.

How do I get notification that the player name array has changed?

EDIT: Does the iOS SDK even support NSArrayController? If not, is there another way?

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

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

发布评论

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

评论(1

奶茶白久 2024-09-21 21:57:16

您不需要 NSArrayController 来观察 NSArray 的更改。但是您无法直接观察这些更改,即您无法直接在 NSArray 上调用 -addObserver:forKeyPath:options:context:。在您的情况下,您希望使用 @"playerNameArray" 作为键在 GameModel 上调用它。

但你还没有完成。仅当您调用 -setPlayerNameArray: 时,普通的自动 KVO 通知才会启动,从而替换整个数组。如果您想要更精细的通知,则每当插入、删除或替换项目时,您都需要使用 -willChange:valuesAtIndexes:forKey:-didChange:valuesAtIndexes:forKey:在那个数组中。

每当数组的内容发生变化时,就会发送通知。根据添加观察者时使用的 NSKeyValueObservingOptions ,您还可以获得所做的增量更改——这是一个很酷的功能,但在这种情况下您可能不需要它。

注意:iOS 上不存在 NSArrayController。它是 Cocoa Bindings 的一部分,目前仅存在于 Mac OS X 上的 AppKit 中。幸运的是,您不需要它。

You don't need an NSArrayController to observe changes to an NSArray. However you cannot directly observe these changes, i.e., you can't call -addObserver:forKeyPath:options:context: directly on an NSArray. In your case you want to call it on your GameModel with @"playerNameArray" as the key.

You're not done yet though. The normal automatic KVO notifications will only kick in if you call -setPlayerNameArray:, thereby replacing the entire array. If you want more granular notifications, then you need to use -willChange:valuesAtIndexes:forKey: and -didChange:valuesAtIndexes:forKey: whenever you insert, remove, or replace items in that array.

This will send a notification whenever the contents of the array changes. Depending on the NSKeyValueObservingOptions you use when adding your observer, you can also get the incremental changes that are made—a cool feature, but you may not need it in this case.

Note: NSArrayController does not exist on iOS. It's part of Cocoa Bindings, which currently only exists in AppKit on Mac OS X. Luckily, you don't need it.

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