Reputation: 75
I am trying to implement the Key Value Observation pattern and in most the process have worked well but my newValue and oldValue are same even though the value has changed from old value to new value. Here is the sample code of what I have implemented so far. It will be great if someone can tell me where I have got this wrong.
@property (strong, nonatomic) NSString* selectedRow;
Adding Observer
[self addObserver:self
forKeyPath:@"selectedRow"
options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
context:NULL];
Method where value will be updated
-(void) methodToChangeValue {
self.selectedRow = [self.tableView indexPathForCell:[selectedCell]];
//Above line is dummy that will get the row for indexPath and set the selected row, I wanted to pass that row to selectRow key
}
Observer call
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSString* oldValue = [change valueForKey:NSKeyValueChangeOldKey];
NSString *newValue = [change valueForKey:NSKeyValueChangeNewKey];
NSLog(@" old value %@ and new value %@", oldValue,newValue);
}
** Old value and new value are same even though I changed the value from the method.
Thanks
Upvotes: 0
Views: 50
Reputation: 318774
Your problem are these lines:
_selectedRow = [self.tableView indexPathForCell:[selectedCell]];
[self setValue:_selectedRow forKey:@"selectedRow"];
Why are you doing this? Why not do it the proper way:
self.selectedRow = [self.tableView indexPathForCell:[selectedCell]];
If you do it that way, the KVO will work properly. As you have it now, you are setting the instance variable directly (which bypasses KVO) and then you use KVC to set the property to the same value as its own instance variable. Since you are setting the property to its own value, your observer sees the old and new values as the same.
You are also using the wrong data type for selectedRow
. It needs to be NSIndexPath
instead of NSString
. Same for getting the old and new values. Use NSIndexPath
.
Upvotes: 1