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 »

5 Responses to “Talking to my self”

  1. Brian Webster

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

    *cackles maniacially*

  2. Devin Coughlin

    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

    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

    Good points all around.

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

  5. Steve Steinitz

    Hi,

    Thanks for explaining the graphics flipping. It would have taken me a week to figure it out.

    All the best,

    Steve


Leave a Reply



Back to top