I have been knocking my head against the wall trying to figure whether it is possible to call a function defined in a different class. Unfortunately, my limited knowledge in Objective C prevented me to reach a satisfactory answer. Basically, I have one class called Caller and a different class called Functions that I would like to hook to at run time. Class Functions will have all the functions defined that caller is going to reference to at run time.
This is the code in its entirety:
--- Caller.h -------------------
#import "Functions.h"
@interface Caller
{
int callerId;
NSMethodSignature *sig;
NSInvocation *func;
}
@property(retain) NSInvocation* func;
@end
--- Caller.m -------------------
#import "Caller.h"
@implementation Caller
@Synthesize func;
-(id)initWithFunction: (SEL)f
{
if (self)
{ Sig = [Caller instanceMethodSignatureForSelector: f];
func= [NSInvocation invocationWithMethodSignature: Sig];}
return self;
}
@end
--- Functions.h -------------------
@interface Functions
-(int)SayHello;
@end
--- Functions.m -------------------
#import "Functions.h"
@implementation
-(int)SayHello
{
NSLog(@"Hello");
return 0;
}
---------main.m-----------------
#import <Foundation/Foundation.h>
#import "Caller.h"
#import "Functions.h"
int main
{
NSAutoreleasePool * pool [[NSAutoreleasePool alloc]init];
Functions* ftn = [[Functions alloc]init];
Caller * c = [[Caller alloc]initWithFunction: @selection(SayHello)];
[c.func setTarget:c];
[c.func invoke];
[pool drain];
return 0;
}
The code was compiling fine but at run time, it encountered an error because instanceMethodSignatureForSelector is 0. If I make Caller class inherit from Functions class, then the program will work like a charm. But Functions class in my case has to be independent from Caller class. Is there a work around?
+instanceMethodSignatureForSelector:returnsnilbecauseCallerdoesn’t have such a method – it is implemented in another class which you can’t know with the given data at that point.Instead you can retrieve the method signature from the target later, e.g.: