Key Value Observing with an NSArray

后端 未结 1 1249
情话喂你
情话喂你 2020-12-04 22:48

I\'ve looked on SO for examples of using Key Value Observing with an NSArray (or NSMutableArray) and apparently you need to use an NSArrayCon

相关标签:
1条回答
  • 2020-12-04 23:14

    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.

    0 讨论(0)
提交回复
热议问题