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

2019-05-31 01:08发布

问题:

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");
}

回答1:

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".



回答2:

NSDictionary is not Key-Value Observing compliant. You simply cannot observe changes to a dictionary using KVO. Even if it appears to work for some cases it may break in a future version.