I’ve been learning Objective-C and was implementing a regular expression library on top of libpcre. I wanted to add a way of accepting a user-defined function in replace operations, similar to Ruby’s
String.gsub() or Perl
I realized that I needed to handle callbacks, but in Objective-C, you’re not supposed to play with function pointers.
In C or C++ the pattern is very common, but I was initially stumped when I had to implement the same pattern in Objective-C. All the search results I got seemed to say you couldn’t do it.
The C Way
In C you pass the callback function as a function pointer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Which results in:
$ ./callback 'caller' invoking callback 'my_callback' called with greeting 'Hello C'
Selector From String
In Objective-C you don’t actually call methods. You send messages to objects, and the Objective-C runtime invokes the correct method by matching the message signature with available selectors for that object.
What follows is GNUStep-specific, but should work with Apple’s Objective-C method
An Objective-C Equivalent
Here’s the object we want to call back to, it has a method which takes one parameter:
1 2 3 4 5 6 7 8 9 10
Here’s the calling code.
1 2 3 4 5 6 7 8 9 10 11 12
The name of the method we want to call is
my_callback: - note the
1 2 3 4 5 6
The result of all this is:
$ ./callback Caller invoking method 'my_callback:' 'Responder.my_callback' called with greeting: 'Hello Objective-C'.
This seems rather long-winded, but in the end most of the extra lines of code here relate to the fact we’re using objects, not plain functions as we do in C.
The next step would be to benchmark this to get an idea how much time the Objective-C runtime takes to do the method lookup with
GSSelectorFromName and to carry out the call.