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