Usage of Objective-C function pointer

If you want to pass a function methodA in ClassA to ClassB and call it directly,

Here you need to use function pointers. Of course, you can pass the ClassA object to ClassB, but this is not discussed here.

Special scenarios require, and sometimes, a pointer to a function is indeed required for use. Here, ClassA and ClassB are used as examples. The final realization is to define a pointer in ClassA in ClassB for calling.

First we define an Interface of ClassA:

// ClassA.h
@interface ClassA : NSObject
- (void)methodA:(NSString *)string;
@end

// ClassA.m
@implementation ClassA
- (void)methodA:(NSString *)string {
    NSLog(@"Hello from methodA: %@", string);
}
@end

Then we define a function pointer MethodPointer in ClassB, as follows:

// ClassB.h
@interface ClassB : NSObject
typedef void (^MethodPointer)(NSString *);
@property (nonatomic, copy) MethodPointer methodPointer;
- (void)methodB;
@end

// ClassB.m
@implementation ClassB
- (void)methodB {
    if (self.methodPointer) {
        self.methodPointer(@"Hello from methodB");
    }
}
@end

In the class method of ClassB, methodB is to call the function pointer methodPointer, which actually calls the function in ClassA.

The method of use is as follows:

int main(int argc, const char * argv[]) {
    //初始化ClassA
    ClassA *a = [[ClassA alloc] init];
    //初始化ClassB
    ClassB *b = [[ClassB alloc] init];
    //把调用ClassA中的methodA的函数指针赋予给methodPointer指针
    b.methodPointer = ^(NSString *string) {
        [a methodA:string];
    };
    //调用ClassB中的函数methodB
    [b methodB];
}

The above is the usage of function pointers in Object-C, which is actually similar to that in C++.

Guess you like

Origin blog.csdn.net/wangmy1988/article/details/130110816