问题描述
我已经在SO上找到了使用NSArray
(或NSMutableArray
)使用键值观察的示例,显然您需要使用NSArrayController
(与我不熟悉的KVO
不同) ,但是我还没有找到具体方法来做到这一点.谁能解释一些示例代码?
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?
例如,如果我有一个GameModel
,其NSArray (playerNameArray)
为NSStrings
表示其玩家名称.我想观察那些字符串(视图控制器观察模型的数据)以更新视图中的各种内容.
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?
编辑:iOS SDK甚至支持NSArrayController
吗?如果没有,还有其他方法吗?
EDIT: Does the iOS SDK even support NSArrayController
? If not, is there another way?
推荐答案
您不需要NSArrayController即可观察对NSArray
的更改.但是,您不能直接观察这些变化,即,不能直接在NSArray
上调用-addObserver:forKeyPath:options:context:
.在您的情况下,您想在GameModel
上以@"playerNameArray"
作为键来调用它.
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.
您尚未完成.普通的自动KVO通知仅在您调用-setPlayerNameArray:
时才起作用,从而替换了整个阵列.如果您希望获得更详细的通知,则每次在该数组中插入,删除或替换项目时都需要使用-willChange:valuesAtIndexes:forKey:
和-didChange:valuesAtIndexes:forKey:
.
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.
每当数组内容更改时,这将发送一条通知.根据添加观察者时使用的NSKeyValueObservingOptions
,您还可以获取所做的增量更改-一个很酷的功能,但是在这种情况下您可能不需要它.
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.
注意:iOS上不存在NSArrayController.它是Cocoa绑定的一部分,目前仅在Mac OS X上的AppKit中存在.幸运的是,您不需要它.
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.
这篇关于使用NSArray进行键值观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!