我有一个绑定到阵列控制器的模型.我需要能够直接更新模型并向阵列控制器发送有关更新的通知.在我的搜索中,我发现我可以通过mutableArrayValueForKey:在我的模型上使用并通过返回的NSMutableArray进行更新来实现这一点.
我还发现了一些引用让我相信我也可以更新模型并在我实现并使用KVC兼容的getter和可变索引访问器时发送通知.在我的代码中我实现了
-countOf<Key>:
-objectIn<Key>AtIndex:
-insertObject:in<Key>AtIndex:
-removeObjectFrom<Key>AtIndex:
Run Code Online (Sandbox Code Playgroud)
通话insertObject:in<Key>AtIndex:并未导致我的观察员收到通知.下面的代码是我可以想出的最小的部分来测试我想要做的事情.
#import <Foundation/Foundation.h>
@interface ModelAndObserver : NSObject {
NSMutableArray *theArray;
}
@property(retain)NSMutableArray *theArray;
- (NSUInteger)countOfTheArray;
- (NSString *)objectInTheArrayAtIndex:(NSUInteger)index;
- (void)insertObject:(NSString*) string inTheArrayAtIndex:(NSUInteger)index;
- (void)removeObjectInTheArrayAtIndex:(NSUInteger)index;
@end
@implementation ModelAndObserver
@synthesize theArray;
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
NSLog(@"theArray now has %d items", [theArray count]);
}
- (NSUInteger)countOfTheArray
{
return [theArray count];
}
- (NSString *)objectInTheArrayAtIndex:(NSUInteger)index
{
return [theArray objectAtIndex:index];
}
- (void)insertObject:(NSString*) string inTheArrayAtIndex:(NSUInteger)index
{
[theArray insertObject:string atIndex:index];
} …Run Code Online (Sandbox Code Playgroud)