Passing function as argument to Objective-C method
I'd like to pass a C
function as an argument to an Objective-C method, to then act as a callback. The f开发者_如何学JAVAunction has type int (*callback)(void *arg1, int arg2, char **arg3, char **arg4)
.
I keep getting the syntax wrong. How do I do this?
As a slightly more complete alternative to KKK4SO's example:
#import <Cocoa/Cocoa.h>
// typedef for the callback type
typedef int (*callbackType)(int x, int y);
@interface Foobar : NSObject
// without using the typedef
- (void) callFunction:(int (*)(int x, int y))callback;
// with the typedef
- (void) callFunction2:(callbackType)callback;
@end
@implementation Foobar
- (void) callFunction:(int (*)(int x, int y))callback {
int ret = callback(5, 10);
NSLog(@"Returned: %d", ret);
}
// same code for both, really
- (void) callFunction2:(callbackType)callback {
int ret = callback(5, 10);
NSLog(@"Returned: %d", ret);
}
@end
static int someFunction(int x, int y) {
NSLog(@"Called: %d, %d", x, y);
return x * y;
}
int main (int argc, char const *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Foobar *baz = [[Foobar alloc] init];
[baz callFunction:someFunction];
[baz callFunction2:someFunction];
[baz release];
[pool drain];
return 0;
}
Basically, it's the same as anything else, except that without the typedef, you don't specify the name of the callback when specifying the type of the parameter (the callback
parameter in either callFunction:
method). So that detail might have been tripping you up, but it's simple enough.
The following peice of code worked,absolutely fine . just check
typedef int (*callback)(void *arg1, int arg2, char **arg3, char **arg4);
int f(void *arg1, int arg2, char **arg3, char **arg4)
{
return 9;
}
-(void) dummy:(callback) a
{
int i = a(NULL,1,NULL,NULL);
NSLog(@"%d",i);
}
-(void) someOtherMehtod
{
callback a = f;
[self dummy:a];
}
精彩评论