2

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.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
Meltemi
  • 37,979
  • 50
  • 195
  • 293
  • [NSString stringWithFormat:@"myObject.value"] is redundant, it's using a format that doesn't have any arguments. You should probably just use @"myObject.value". – Jon Hess Jul 08 '09 at 21:21

3 Answers3

9

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.

Barry Wark
  • 107,306
  • 24
  • 181
  • 206
7

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.

Chuck
  • 234,037
  • 30
  • 302
  • 389
1

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"];
Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
Jason
  • 1,323
  • 14
  • 19