Search code examples
iphoneiosobjective-cipadkey-value-observing

KVO questions in a data source


I have a UITableView with a data source of NewsItem objects that is stored in an array. In my NewsItem object I have a BOOL called 'imageState' that I wanted to be tracked. I wanted to use KVO such that when the value of this imageState changed then the UIViewController that has the NewsItem array be notified and it would then do some stuff (i.e: reloading the cells or something). How do I do something like this? Is it first of all doable?


Solution

  • you can add the observer in the TableViewController , like this

    [self addObserver:newsItemObject  forKeyPath:@"imageState" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
    

    it will observering the object , and when it change it will call this method , you should implement this method below:

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
     NSLog(@"%@ \n %@ \n %@ \n ",keyPath,object,change);
     // do your things
    }
    

    if class NewsItem is your class , I think it is better use Delegate or Notification . The KVO is not a better way .