1.把block保存成对象中的属性,在恰当的时刻调用
1.png
2.把block当成方法的参数使用,block的调用在是在方法内部,在外界写block的实现(最常用)
2.png
3.把block当成方法的返回值(比较少用)
3.png
示例1
1.在Person类中
@interfacePerson:NSObject@property(nonatomic,copy)void(^myBlock)(int,int);
@end
2.在ViewController类中
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{inta =12;intb =11;
Person *p = [[Person alloc] init];
p.myBlock(a,b);
}
示例2
1.在Person类中
@interfacePerson:NSObject- (void)eat:(void(^)())block;
@end
@implementation Person
- (void)eat:(void(^)())block{
block();
}
@end
2.在ViewController类中
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{
// 方式1.先定义,在赋值
// void(^block)() = ^() {
// NSLog(@"吃东西");
// };
//// [p eat:block];
// 方式2.直接写
block[p eat:^{
NSLog(@"吃东西");
}];
}
示例3
1.在Person类中
@interfacePerson:NSObject
- (void(^)(int))run;
@end
@implementation Person
- (void(^)(int))run{
return^(into){
NSLog(@"跑了--%d米",b);
};
}
@end
2.在ViewController类中
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{
p.run(5);
}
网友评论