block可以保存一段代码,在需要的时候调用
1)定义一个没有参数没有返回值block
参数类型void(^)() block变量名
void(^block)() =^ (){
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
};
调用: block();
给block起别名的方式定义
// MyBlock类型名
MyBlock block1 =^{
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
};
调用: block1();
2)在开发中一般都是跨方法调用
@property (nonatomic, copy) MyBlock block2;
typedefvoid(^MyBlock)();
@property(nonatomic,copy)void(^myBlock)(NSString*) ;
//保存代码
self.block2 =^{
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
};
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{
//调用block
self.block2();
}
3)block当做参数传递
[UIView animateWithDuration:0 animations:^{
}completion:^(BOOLfinished) {
}];
}
网友评论