【发布时间】:2011-08-07 23:41:41
【问题描述】:
我的 AppDelegate 中有一个 NSMutableArray 属性,称为块。 我想观察何时将对象添加到此数组中。 我读过其他帖子,但我不明白为什么这不起作用。
在我的应用委托类中,我实现了
- (void)insertObject:(id)obj inBlocksAtIndex:(NSInteger)index
{
[blocks insertObject:obj atIndex:index];
}
在我的视图控制器的 init 方法中,我向我的 AppDelegate 引用添加了一个观察者。
boardModel = [[UIApplication sharedApplication] delegate];
[boardModel addObserver:self forKeyPath:@"blocks" options:0 context:NULL];
在我的视图控制器的 viewDidLoad 方法中,我尝试调用我之前实现的 KVO 索引数组访问器,
[boardModel insertObject:[[Block alloc] init] inBlocksAtIndex:0];
然后我实现了我的 observeValueForKeyPath 方法:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"blocks"])
{
NSLog(@"ADDED");
}
}
我试过在observeValueForKeyPath的if语句之前添加一个NSLog语句,看起来好像从来没有被调用过。
我也试过 NSLogging [[boardModel blocks] count],它说计数是 1(正在添加对象)。
我一定是错过了什么。
【问题讨论】:
标签: objective-c