Call objc methods that contain an underscore
lukaskollmer last edited by
How can I use
objc_utilto call Objective-C methods that contain underscores?
Usually, I'd write
object._doSomethingWithParameter_(param), but the problem is that only the second underscore indicates a parameter. The first one is part of the method name. Pythonista however will convert that to the selector
:doSomethingWithParameter:, which requires two parameters.
How do I call the following method:
- (void)_addActionWithTitle:(id)arg1 image:(id)arg2 style:(int)arg3 handler:(id)arg4;
omz last edited by omz
objc_utilshould usually be smart enough to figure this out automatically. If you attempt to call
_doSomethingWithParam_, it will first try to translate that to
:doSomethingWithParameter:, but if that method doesn't exist (which is very likely), it'll try all permutations of underscores and colons for replacing the underscores in the method name, and it should eventually arrive at
_doSomethingWithParameter:(in this case, there are only 4 possible permutations).
There could theoretically be cases where both
:doSomethingWithParameter:are valid methods (unlikely, but possible) – in those cases, you could construct an
ObjCInstanceMethodmanually like this:
ObjCInstanceMethod(some_obj, '_doSomethingWithParameter:'). This would also be slightly faster because there's no guessing involved to figure out the correct selector.
Long story short, calling
_addActionWithTitle_image_style_handler_should "just work".