我正在尝试使用KVC更新一些属性。这些属性已经合成。
此行有效:
myObject.value = intValue;
这不起作用:
[self setValue:[NSNumber numberWithInt:intValue] forKey:@"myObject.value"];
然后爆炸:由于未捕获的异常'NSUnknownKeyException'终止应用程序,原因:'[< MyViewController 0xd1cec0> setValue:forUndefinedKey:]:此类不是密钥myObject.value的键值编码兼容。'
然而,该方法(awakeFromNib)的其他实例还可以对setValue:forKey:calls做出很好的响应。唯一的区别是这个特定的实例是在IB中创建和连接的。
答案 0 :(得分:9)
您无法将关键路径作为第二个参数传递给-[NSObject setValue:forKey:]
。您想要使用setValue:forKeyPath:
代替:
[self setValue:[NSNumber numberWithInt:intValue] forKeyPath:@"myObject.value"];
我的理解是setValue:forKey:
是作为性能优化提供的。由于它不能采用密钥路径,因此不必解析密钥字符串。
答案 1 :(得分:7)
它告诉你这不是该对象的有效密钥,实际上它不是:“myObject.value”是一个密钥路径,而不是一个密钥。
答案 2 :(得分:1)
我同意查克。
我认为你需要这样做:
[self setValue:[NSNumber numberWithInt:intValue] forKeyPath:@"myObject.value"];
或通过关键路径的每个部分,如:
id myObject = [self objectForKey:@"myObject"];
[myObject setValue:[NSNumber numberWithInt:intValue] forKey:@"value"];