views:

109

answers:

2

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?

+7  A: 

The following works for me, returning foo:

id myObj = [foo valueForKey: @"self"];
Costique
that's cool! I didn't know you could do that. =)
Dave DeLong
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
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
I didn't know that this is possible, but if I think about it, it is not so surprising.
swegi
@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
+3  A: 
id myObj = foo;
swegi
That was a perfectly valid question about KVC, by the way :)
Costique
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