我正在尝试使用键值观察来为NSMutableArray工作.下面是MyObservee的.h文件,观察到的类:
@interface MyObservee : NSObject { @private int someValue; @private NSMutableArray *someArray; } @property (readwrite,assign) int someValue; - (NSMutableArray *)someArray; @end
MyObserver类实现observeValueForKeyPath:ofObject:change:context:.这是我添加观察者的方式:
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键路径的更改而触发?我觉得这里有一些我不完全理解的东西.
您需要实现KVC编程指南中定义的索引数组访问器.然后,您必须使用这些访问器来访问阵列,KVO触发将起作用.您还可以调用-mutableArrayValueForKey:并将该数组用于addObject:等等,它将依次调用访问器方法,并且也会发生KVO触发.还有用于NSSets的设置访问器,请参见此处和此处.
例:
@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