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

蓝咒 提交于 2020-01-03 03:22:07

问题


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.



来源:https://stackoverflow.com/questions/14172774/kvo-doesnt-work-with-keypath-like-com-alpha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!