之前我曾使用过NSNotifications,但这是我第一次尝试在Cocoa Touch中使用KVO。
我的UITableView控制器在各种数据源之间切换,因此我将它们封装在不同的UITableViewDataSource子类中。我正在尝试让我的视图控制器观察这些UITableViewDataSource子类中的特定一个,并跟踪一个名为loadState
的枚举,它反映了加载状态的模型。
我像这样设置观察者:
[self.siteUpdatesDataSource addObserver:self
forKeyPath:@"loadState"
options:0
context:nil];
从调试器中我可以看到观察者已注册:
(gdb) po [self siteUpdatesDataSource]
<SiteUpdatesTableViewDataSource: 0x651e5a0>
Current language: auto; currently objective-c
(gdb) po [[self siteUpdatesDataSource] observationInfo]
<NSKeyValueObservationInfo 0x651dd70> (
<NSKeyValueObservance 0x651dd10: Observer: 0xc80f1e0, Key path: loadState, Options: <New: NO, Old: NO, Prior: NO> Context: 0x0, Property: 0x651dd90>
)
但是,我的viewController中的observeValueForKeyPath方法似乎永远不会被调用。我设置了一个断点,即使我确认枚举已经改变,也没有任何东西可以达到它。
- (void) observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
[self.tableView reloadData];
}
我很欣赏任何关于我失踪的想法。
答案 0 :(得分:9)
看不出任何问题。您确定通过调用合成访问者或使用KVC或手动更改loadState
属性(通过willChangeValueForKey:
和didChangeValueForKey:)
通知有关更改吗?