需要理解Object-C中的Block,需要先了解一下函数指针。函数指针是C语言定义的一种指针,用于指向一个函数。
在C语言中,函数名在compiler看来,就是一个地址值。而函数指针可以接收一个地址。所以可以用函数指针等于一个函数名。
具体看下下面的demo:
typedef char * (*Fp)(char *p1, char *p2); // define alias of an function pointer
// define an function to return the unique string
char *returnString(char *s1, char *s2) {
int i = 0;
char *finalString = NULL;
i = strcmp(s1, s2);
finalString = (i != 0)? s1 : s2;
return finalString;
}
上面的连段代码分别定义了一个叫Fp的函数指针,以及定义了一个返回char *的指针函数returnString
现在来看函数指针如何使用。
Fp f1;
printf("the address of f1 is: %p\n", f1);
f1 = returnString; // function pointer f1 to point to an function which defined before main function
char *result = f1("hello", "friends"); // to call function returnString by using Fp
printf("this result is: %s\n", result);
printf("the address of returnString is: %p\n", returnString);
printf("the address of f1 is: %p\n", f1);
f1 = NULL;
printf("the address of f1 is: %p\n", f1);