Search code examples
iphoneuitableviewafnetworkingkey-value-observing

KVO update UITableViewCell


I have a ViewControllerA that you can download files using AFNetworking and setDownloadProgress to update my model with the progress. I also have ViewControllerB that has a UITableView with a list of all the transfers.

Inside cellForRowAtIndexPath I observer my model

[transfer addObserver:cell
           forKeyPath:@"completed"
              options:NSKeyValueObservingOptionNew
              context:NULL];

This works, and I can read the progress like

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"completed"]) {
        float val = [[change objectForKey:@"new"] floatValue];
        NSLog(@"%f", val);
    }
}

But I don't know how I can update my UITableViewCell with my KVO?


Solution

  • The easiest way I've found is to subclass UITableViewCell, and add your observations there.

    @implementation MyCustomCell
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if ([keyPath isEqualToString:@"completed"]) {
            float val = [[change objectForKey:@"new"] floatValue];
    
            // assuming that you're trying to update a label within your cell
            self.progressLabel.text = [NSString stringWithFormat:@"%f %%", val];
        }    
    }