6

Given an object foo of class Foo, I want to do the following:

NSString *key = @"some key";
id myObj = [foo valueForKey: key];

and have myObj equal to foo.

Is there a way to do this without defining a category on Foo?

Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
William Jockusch
  • 26,513
  • 49
  • 182
  • 323

2 Answers2

11

The following works for me, returning foo:

id myObj = [foo valueForKey: @"self"];
Costique
  • 23,712
  • 4
  • 76
  • 79
  • Agreed, it is pretty darn cool, and it makes sense that you could ask for it this way. Is there a scenario where this is your only option, though? Perhaps you can only send a key path query to an object for which you don't have a pointer to its owning object? Sounds like an odd situation... – Quinn Taylor Feb 05 '10 at 06:34
  • Yes, I admit I can't think of any real-world situation where I would really need this. But the coolness of @"self" is in its existence. I guess if you come across the rare case where you have to heavily rely on KVC, you will owe the engineer who did it a truckload of beer. – Costique Feb 05 '10 at 07:07
  • I didn't know that this is possible, but if I think about it, it is not so surprising. – swegi Feb 05 '10 at 08:01
  • 1
    @Quinn Taylor: it's good for sort descriptors that need a keypath, and you're sorting the actual object in the array, rather than a property of the object. i.e. an array of `NSNumber` – ohhorob Jul 08 '10 at 21:08
3
id myObj = foo;
swegi
  • 4,046
  • 1
  • 26
  • 45
  • That was a perfectly valid question about KVC, by the way :) – Costique Feb 04 '10 at 15:44
  • Occam's Razor strikes again. I tend to agree with this answer — if you can get a pointer to message an object, just use that pointer. I understand this is probably just an academic exercise, but why spend cycles on key-value observing when the answer is obvious? – Quinn Taylor Feb 05 '10 at 06:32