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.

4 Comments »

  1. Brian Webster Said,

    October 9, 2007 @ 11:00 pm

    Ah yes, but what about [someObject valueForKeyPath:@"self.self.self.self.self.self"]?

    *cackles maniacially*

  2. Devin Coughlin Said,

    October 9, 2007 @ 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.

  3. Jeff Johnson Said,

    October 9, 2007 @ 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. ;-)

  4. mr_noodle Said,

    October 10, 2007 @ 12:02 am

    Good points all around.

    Devin: Since you’re the odd-man out, I suggest you register “fatlapsoftware.com”

RSS feed for comments on this post

Leave a Comment

- Why ask? This confirms you are a human user!