В качестве чуть более полной альтернативы примеру KKK4SO:
#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;
}
По сути, это то же самое, что и все остальное, за исключением того, что без typedef вы не указываете имя обратного вызова при указании типа параметра (параметр callback
в любом из методов callFunction:
). Так что эта деталь могла сбить вас с толку, но она достаточно проста.