For Objective-C … Pointer to method
-
23-08-2019 - |
Question
I want to setup a Method dispatch table and I am wondering if it is possible to create pointer to a method in Objective-C (like pointer to function in C). I tried to use some Objective-C runtime functions to dynamically switch methods but the problem is it will affect all instances.
As I am very new to Objective-C, an illustrated example would be highly appreciated.
Solution
Objective-C methods are called selector
s, and are represented by the SEL
datatype. If your object inherits from NSObject
, you can tell it to perform a selector (i.e. call a method) like thus:
SEL selector = @selector(doSomething:);
[obj performSelector:selector withObject:argument];
This assumes you have a method defined such as:
-(void)doSomething:(MyObject*)arg;
Selectors are assigned to SEL
datatypes through the @selector
keyword, which takes the name of the method you would like to keep. The name of the method is the method name stripped of all arguments. For example:
-(void)doSomething:(MyObject*)arg withParams:(MyParams*)params
Would be referenced as @selector(doSomething:withParams:)
.
OTHER TIPS
Yes! In Objective-C, function pointers are called selectors. If you have a method defined like this:
- (void)myFunctionWithObject:(NSObject*)obj otherObject:(NSNumber*)obj2
{
}
The selector is declared like this:
@selector(myFunctionWithObject:otherObject:)
To perform a selector on an object, you can use:
[object performSelector:@selector(myFunction)];
or
[object performSelector:@selector(myFunctionTakingParameter:) withObject: o];
The selector data type is particularly useful for threads and timers, where you can dispatch a thread and provide it a selector to the message you'd like it to invoke. If you need to create an array of selectors (or a dispatch table), or if you need to invoke selectors with multiple parameters, you can use the NSInvocation class. It provides a wrapper for a selector and allows you to specify actual arguments.
You should keep in mind that Objective-C is already based on a fully dynamic method dispatch table. It sounds like maintaining function pointers using selectors will work fine for you if you just need a reference to a function, though.