Auto-boxing with performSelector:? Nope, but KVC works.

While trying to debug some code I encountered, I came across this article by Marcus Zarra: Does Objective-C Perform Autoboxing on Primitives? 

The article has been retracted. It initially stated that when calling performSelector:withObject: on a method that took a primitive argument, you could pass in an NSNumber and Cocoa would unbox it for you. However, it turns out that the trick does not in fact work, so the article comes with a big disclaimer at the top.

If you’re ever in that situation, where you need to call a method that takes a primitive argument indirectly, what should you do? There are a number of ways, such as using NSInvocation, or working with the method’s IMP directly, both of which I may talk about further in another article. There’s one more way though: humble Key Value Coding.

It turns out KVC does perform auto-unboxing for you. So if the method you are trying to call meets the criteria for a KVC method (e.g. it is in the form setSomething:,), you can do this:

- (void)start;
{
    [self setValue:@(1415) forKey:@"aThingy"];
}

- (void)setAThingy:(int)anInt;
{
    NSLog(@"An int: %d", anInt);
}

This will work with some other primitive types too, including BOOLs, floats, and even structs wrapped in an NSValue. The complete list is found in Apple’s Key Value Coding documentation.

Previous
Previous

Omni Frameworks part 3: saving some data

Next
Next

Threads — an idea for an App.net client