最近面试碰到一个block的问题:写个函数,返回输出int传参的block.之前正好看了ASI怎么宏定义block,就写上了:
typedef PrintBlock (^ void)(int num)
- (PrintBlock)getBlock:(int)num {
return ^(int num){ NSLog(@"%d",num); };
}
思路体现出来了,不过各种细节错误,囧...
其实就考两点,block定义和内存管理.
1.定义,看文档吧:
A block variable looks like a function pointer, except with a caret (‘^’) instead of an asterisk (‘*’).
void (^my_block)(void);
前面加个typedef就成了类型声明,如ASI的:
typedef void (^ASIXXXBlock)(void)
PS:昨天看文档的runtime guide,才晓得fuction pointer是咋声明的,果然*跟^渊源很深
2.内存管理,关键在于block是栈分配的变量,当前作用域结束它就会释放.文档在此:
Memory Management
Internally, a block object is implemented as a function pointer plus context data and optional support routines. It is allocated directly on the stack for efficiency, which means that you need to copy a block to the heap (and release it when you are done) if you want it to persist outside its initial scope.
再看头文件对dispatch_block_t的定义,会有更直观的印象,因为注释里还举例了^^
至此OK,得到:
typedef void (^PrintBlock)(int num);
@interface ClassA : NSObject {
}
+ (PrintBlock)createBlock;
@end
@implementation ClassA
+ (PrintBlock)createBlock {
PrintBlock block = ^(int num){ NSLog(@"%d",num); };
return [block copy];
}
@end