关于KVO和方法“observeValueForKeyPath”的问题

时间:2011-08-23 18:17:44

标签: objective-c key-value-observing

你能帮我理解observeValueForKeyPath方法:

这里似乎调用observeValueForKeyPath是因为我们更改了“key:earthquakeList”的值,但是假设我们有另一个关键点,比如“earthquake_New_List”,

如果我们只有一个回调方法,observeValueForKeyPath?

我怎么知道观察到的第一个或第二个键已经改变了?
[self addObserver:self forKeyPath:@"earthquakeList" options:0 context:NULL];
//...
- (void)insertEarthquakes:(NSArray *)earthquakes
{
    // this will allow us as an observer to notified (see observeValueForKeyPath)
    // so we can update our UITableView
    //
    [self willChangeValueForKey:@"earthquakeList"];
    [self.earthquakeList addObjectsFromArray:earthquakes];
    [self didChangeValueForKey:@"earthquakeList"];
}

// listen for changes to the earthquake list coming from our app delegate.
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    [self.tableView reloadData];
}

由于

1 个答案:

答案 0 :(得分:3)

keyPath实施中的observeValueForKeyPath:ofObject:change:context:参数会告诉您哪个密钥已更改。所以你可以这样做:

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if ([keyPath isEqualToString:@"key1"]) {
        // do something
    } else if ([keyPath isEqualToString:@"key2"]) {
        // do something else
    }
}