Cocoa KVC: “class is not key value coding-compliant”

空扰寡人 提交于 2019-12-24 05:22:07

问题


I'm trying to update some properties with KVC. The properties have been synthesized.

This line works:

myObject.value = intValue;

This doesn't work:

[self setValue:[NSNumber numberWithInt:intValue] forKey:@"myObject.value"];

And blows up with: Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<MyViewController 0xd1cec0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key myObject.value.'

Yet further up the method (awakeFromNib) other instances of the same class respond fine to setValue:forKey: calls. The only difference is this particular instance was created and wired up in IB.


回答1:


It's telling you that isn't a valid key for that object, and indeed it isn't: "myObject.value" is a keypath, not a single key.




回答2:


You cannot pass a key path as the second argument to -[NSObject setValue:forKey:]. You want to use setValue:forKeyPath: instead:

[self setValue:[NSNumber numberWithInt:intValue] forKeyPath:@"myObject.value"];

My understanding is that setValue:forKey: is provided as a performance optimization. Since it cannot take a key path, it doesn't have to parse the key string.




回答3:


I agree with Chuck.

I think you need to do this instead:

[self setValue:[NSNumber numberWithInt:intValue] forKeyPath:@"myObject.value"];

or via each part of the key path like:

id myObject = [self objectForKey:@"myObject"];
[myObject setValue:[NSNumber numberWithInt:intValue] forKey:@"value"];


来源:https://stackoverflow.com/questions/1100101/cocoa-kvc-class-is-not-key-value-coding-compliant

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