Talking to my self
I have code that takes in a string and uses key-value coding to extract a value from an object. It works fine if you want to get a property of an object, but what about getting the object itself? Using nil
or an empty string with -valueForKey:
or -valueForKeyPath:
causes it to call -valueForUndefinedKey:
which, by default, throws an exception.
After some diddling around, I found that you can use the key @"self"
. Doing valueForKey:@"self"
on an object returns that object. There’s no magic here. NSObject has a -self
method which returns, crazily enough, itself. This is peculiar because on the surface, this method is useless. Anywhere where you can type [anObject self]
you can type anObject
instead. Where this method comes in handy is in cases where you dynamically call a method/selector, as in KVC, and you want to specify a method that is a short-circuit of sorts.
So, in short, all of the following are equivalent:
someObject
[someObject self]
[someObject valueForKey:@"self"]
[[[someObject valueForKey:@"self"] self] valueForKey:@"self"]
I’m sure someone can use the last one in some Objective-C obfuscation contest.
Category: Cocoa, OS X, Programming 5 comments »
October 9th, 2007 at 11:00 pm
Ah yes, but what about [someObject valueForKeyPath:@”self.self.self.self.self.self”]?
*cackles maniacially*
October 9th, 2007 at 11:20 pm
This is also useful when dealing with NSObjectController and friends. Calling [objectController valueForKeyPath:@”selection”] will return a key-value compliant proxy for the selection whereas calling [objectController valueForKeyPath:@”selection.self”] will return the selected object itself.
October 9th, 2007 at 11:33 pm
Caveat: This technique won’t work for classes that override valueForKey:, such as NSArray and NSDictionary. By the way, Brian Webster, I’m not sure I like your domain name. 😉
October 10th, 2007 at 12:02 am
Good points all around.
Devin: Since you’re the odd-man out, I suggest you register “fatlapsoftware.com”
March 11th, 2009 at 6:25 am
Hi,
Thanks for explaining the graphics flipping. It would have taken me a week to figure it out.
All the best,
Steve