How does typedef-ing a block works

情到浓时终转凉″ 提交于 2019-12-03 04:04:37

问题


In C/Obj-C, we do a typedef like this typedef int MYINT; which is clear.

Doing typedef for a block -typedef void (^MyBlock) (int a);

Now, we can use MyBlock.

Shouldn't it be like - typedef void (^MyBlock) (int a) MyBlock; similar to #define?

How the syntax works?


回答1:


See Declaring a Block Reference in "Blocks Programming Topics":

Block variables hold references to blocks. You declare them using syntax similar to that you use to declare a pointer to a function, except that you use ^ instead of *.

So

 typedef void (^myBlock) (int a);

defines a the type of a block using the same syntax as

 typedef void (*myFunc) (int a);

declares a function pointer.

See e.g. Understanding typedefs for function pointers in C for more information about function pointers.




回答2:


Also from "Blocks Programming Topics", creating a type for blocks should be like this:

typedef returnType (^blockName)(argument1, argument2, ...)

Below is a very simple practical example:

typedef float (^MyBlockType)(float, float);
MyBlockType AddTwoFloat = ^(float a, float b) {return a + b;};
MyBlockType MultiplyTwoFloat = ^(float a, float b) {return a * b;};
float c = AddTwoFloat(1, 2); //c = 3
float d = MultiplyTwoFloat(1, 2); //d = 2


来源:https://stackoverflow.com/questions/15310880/how-does-typedef-ing-a-block-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!