块Block我在开发中是经常遇到的,比如服务器返回的处理,消息的传递,GCD等等,多多少少都与Block相关,所以掌握块的细节还是有需要的,块的优势在于能够让系统分配给其他处理器或应用的其他线程执行。
下面简短的代码,了解一下块
1.传入无参
// block
__block int foo = 100;
void (^print_message)(void) = ^(void)
{
NSLog(@"programming is fun %d",foo);
};
foo = 200;
print_message();
NSLog(@"the foo is %d",foo);
2.传入参数
void (^calculateTriangularNumber)(int) = ^(int n)
{
NSLog(@"the power of n is %d",n*n);
};
3.计算最大的公约数
//cal 最大公约数
int (^gcd)(int,int) = ^(int u,int v)
{
int temp;
while(v != 0)
{
temp = u % v;
u = v;
v = temp;
}
return u;
};
块有个强大之处是在她声明的范围内,所有变量都可以为其所捕获。块本身可视为对象,和其它对象一样也有引用计数。块其实就是一种代替函数指针的语法结构。 定义块的时候,其所占的内存区域是分配在栈中的。如果使用copy关键字可以把块复制到堆上面,块从而有了引用计数。
还有一类是全局块,分布在全局区,块所使用的整个内存区,在编译期就已经确定了。
为常用的块类型创建typedof
typedef int (^SWSomeBlock)(int,int){
//Implementation
}
然后使用块
SWSomeBlock block = ^(int aa, int bb){
//Implementation
}
其中SWSomeBlock 就是块的一个别名
如果一个函数的参数是个块,是不是可以得到简化操作,比如UIAlertView的结果处理就不需要在代理里面处理,而采用块的形式。从而达到简化效果。下面是我一段曾经的代码。
<span style="color:#333333;">typedef void (^DCAlertViewBlock)(NSInteger buttonIndex);
@interface DCAlterViewUtil: UIAlertView
-(id)initWithTitle:(NSString *)title
message:(NSString *)message
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles
alterBlock:(DCAlertViewBlock )alterViewBock;
@property (copy,nonatomic) DCAlertViewBlock alerViewBlock;
@end
用块降低代码的分散程度
在开发过程中使用操作网络数据时,针对网络数据的返回常常使用Block处理。
@class SWNetworkFetcher;
typedef void (^SWNetworkFetcherCompletionHandler)(NSData *data);
typedef void (^SWNetworkFetcherErrHander)(NSError *err);
处理函数可以这样写
-(id)initWithURL:(NSURL*)url;
-(void)startWithCompletionHandler:(EWNetworkFetcherCompletionHander)completion
failureHander:(SWNetworkFetcherErrHander)failure;
未完待续,有Block二.......