Key-Value - 观察Cocoa中的一对多关系 [英] Key-Value-Observing a to-many relationship in Cocoa
问题描述
我想让键值观察为一个NSMutableArray工作。下面是MyObservee的.h文件,观察类:
I am trying to get key-value-observing to work for an NSMutableArray. Below is the .h file for MyObservee, the observed class:
@interface MyObservee : NSObject {
@private int someValue;
@private NSMutableArray *someArray;
}
@property (readwrite,assign) int someValue;
- (NSMutableArray *)someArray;
@end
MyObserver类实现了observeValueForKeyPath:ofObject:change:context:。下面是我如何添加观察者:
The class MyObserver implements observeValueForKeyPath:ofObject:change:context:. Here is how I add the observer:
MyObservee *moe = [[MyObservee alloc] init];
MyObserver *mobs = [[MyObserver alloc] init];
[moe addObserver:mobs
forKeyPath:@"someArray"
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:NULL];
[moe.someArray addObject:@"hi there"];
addObject:message如何不触发someArray键路径的更改?我有一个感觉,有一些我不能完全理解这里。
How come the addObject: message isn't triggering as a change to the someArray key path? I have a feeling there's something I don't fully understand here.
推荐答案
你需要实现索引数组访问器定义 KVC编程指南。然后,必须使用这些访问器访问数组,KVO触发器将工作。您还可以调用 - mutableArrayValueForKey:并使用该数组addObject:这样,它会反过来调用访问器方法,KVO触发也会发生。还有用于NSSets的设置访问器,请参阅 here and 此处。
You need to implement the indexed array accessors as defined in the KVC programming guide. Then you must use those accessors to access the array and the KVO triggering will work. You can also call -mutableArrayValueForKey: and use that array to addObject: and such and it will in turn call the accessor methods and the KVO triggering will occur as well. There are also set accessors for use in for NSSets, see here and here.
示例:
@interface MyClass : NSObject
{
NSMutableArray *_orders;
}
@property(retain) NSMutableArray *orders;
- (NSUInteger)countOfOrders;
- (id)objectInOrdersAtIndex:(NSUInteger)index;
- (void)insertObject:(id)obj inOrdersAtIndex:(NSUInteger)index;
- (void)removeObjectFromOrdersAtIndex:(NSUInteger)index;
- (void)replaceObjectInOrdersAtIndex:(NSUInteger)index withObject:(id)obj;
@end
这篇关于Key-Value - 观察Cocoa中的一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!