---
title: "Block再探"
author: "hua397"
date: "2013-04-13T11:18:11Z"
tags: []
categories: ["移动开发"]
slug: "block"
draft: false
lastmod: "2013-04-13T11:19:09Z"
id: 1846754
url: "https://hua397.iteye.com/blog/1846754"
---

最近面试碰到一个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
```