代码如下:
typedef void (^fun) (double a, double b);
double c = 3;
fun multiply = ^(double a, double b) { c = a * b; };
multiply(4, 5);
printf("c = %f\n", c);
注意到这里用了一下typedef,然后问题就是变量c是在multiply定义时一起声明的,c是作为常量来使用的,也就是不能执行c = a * b;这个操作。如果想要修改c的话,一种方法是增加__block前缀?也就是:__block double c = 3;另一种是把c声明为static全局变量? 如:static double c = 3;
这两种方法都是合理的吗?求解答:)
Using
__block
的方法是可行的,但是static
should be written like this:If you want to understand the nature of this problem, it is recommended to read this book "Objective-C Advanced Programming iOS and OS X Multithreading and Memory Management"