- Function Pointers
- The Trouble with Function Pointers
- NSInvocation
- Blocks
- Some Philosophical Reservations
- Summary
- Exercises
The Trouble with Function Pointers
There is one large inconvenience with using function pointers as callbacks or in any situation where you are trying to hand off some code for execution by another part of the program or another thread. Any context that the function requires must be packed up and submitted as a separate variable or variables.
Most designs using callbacks use the pattern shown in Listing 16.1. The function or method that is passed the callback function accepts a blind pointer as an additional argument and then passes that pointer back to the callback function, as shown on Figure 16.2. This is only a minor inconvenience when the context is a single variable as in the preceding example. However, if your function requires a more complicated context, you must create and load a custom structure to hold the context and then pass the pointer to that structure as the context variable. As an alternative, you could package the context variables in an NSDictionary and then pass the dictionary as the context. Either way is awkward if the context involves many variables.
Figure 16.2 Passing a callback function to a method