[英]Cocoa KVC: “class is not key value coding-compliant”
I'm trying to update some properties with KVC. 我正在尝试用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.' 并且爆发: 由于未捕获的异常'NSUnknownKeyException'终止应用程序,原因:'[<MyViewController 0xd1cec0> setValue:forUndefinedKey:]:此类不是密钥myObject.value的密码值编码兼容。
Yet further up the method (awakeFromNib) other instances of the same class respond fine to setValue:forKey: calls. 然而,该方法(awakeFromNib)的其他实例还可以对setValue:forKey:calls做出很好的响应。 The only difference is this particular instance was created and wired up in IB.
唯一的区别是这个特定的实例是在IB中创建和连接的。
You cannot pass a key path as the second argument to -[NSObject setValue:forKey:]
. 您不能将键路径作为第二个参数传递给
-[NSObject setValue:forKey:]
。 You want to use setValue:forKeyPath:
instead: 您想使用
setValue:forKeyPath:
而不是:
[self setValue:[NSNumber numberWithInt:intValue] forKeyPath:@"myObject.value"];
My understanding is that setValue:forKey:
is provided as a performance optimization. 我的理解是
setValue:forKey:
作为性能优化提供。 Since it cannot take a key path, it doesn't have to parse the key string. 由于它不能采用密钥路径,因此不必解析密钥字符串。
它告诉你这不是该对象的有效键,实际上它不是:“myObject.value”是一个键路径,而不是一个键。
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"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.