Search code examples
objective-ckey-value-observing

How to check Key Value Observing in ObjectiveC for dictionary of arrays?


I have the following code:

 @property (strong, nonatomic) NSMutableDictionary *todoSessionDict;
    @synthesize todoSessionDict;

[self addObserver:self forKeyPath:@"todoSessionDict" options:NSKeyValueObservingOptionNew context:NULL];


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

}

------------------------
NSMutableArray *unCompletedTodosArr = [NSMutableArray  array];
NSMutableArray *completedTodosArr   = [NSMutableArray  array];

 [self.todoSessionDict setObject:unCompletedTodosArr forKey:@"unCompletedTodosArr"];
 [self.todoSessionDict setObject:completedTodosArr forKey:@"completedTodosArr"];

Any idea how to check if the @"unCompletedTodosArr" and @"completedTodosArr" values are changed in the self.todoSessionDict using KVO ?


Solution

  • At first, It should be:

     [self addObserver:self forKeyPath:@"todoSessionDict.unCompletedTodosArr" options:0 context:nil];
      [self addObserver:self forKeyPath:@"todoSessionDict.completedTodosArr" options:0 context:nil];
    

    And for both, the methods:

      #pragma mark - KVO
       -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
       {
         // Here your actions depends on the key path...
        }
    
        -(void)didChangeValueForKey:(NSString *)key
    
         {
    
         }