开发者

question about KVO and the method "observeValueForKeyPath"

can you help me understand the observeValueForKeyPath method :

here it seems that observeValueForKeyPath is called because we changed the value "for the key : earthq开发者_运维知识库uakeList" , but let's say we have another key observed, like "earthquake_New_List",

how can i know that the first, or the second key observed, has changed, if we only have one callback method, the 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];
}

Thanks


The keyPath parameter in your implementation of observeValueForKeyPath:ofObject:change:context: will tell you which key has changed. So you can do something like:

- (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
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜