Search code examples
iosobserver-patternkey-value-observing

KVO doesn't work with keypath like com.alpha.


My NSMutableDictionary contains simple keys (@"one", @"two", @"three") and complex keys (@"com.alpha", @"com.beta"). Is it possible to use observers for a complex key?

Observers work well with simple keys, but didn't worked with complex keys. What is a solution?

[self.dict addObserver:self forKeyPath:@"com.alpha" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];

-(IBAction) onChange:(id)sender
{
 [self.dict setObject:@"newValue" forKey:@"com.alpha"];
}

-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
  NSLog(@"____ value had changed");
}

Solution

  • You cannot use keys containing a dot . with key-value-coding or key-value-observing. The dot is used to build a key path that is used to specify a sequence of object properties to traverse. (See Keys and Key Paths in the "Key-Value Coding Programming Guide".)

    For example,

    id x = [object valueForKeyPath:@"com.alpha"];
    

    is the same as

    id x = [[object valueForKey:@"com"] valueForKey:@"alpha"];
    

    For a single key "com.alpha", you will have to rename it to e.g. "com_alpha".