- 1.把block保存成對象中的屬性,在恰當的時刻調用
1.png
-
2.把block當成方法的參數使用,block的調用在是在方法內部,在外界寫block的實現(最常用)
2.png -
3.把block當成方法的返回值(比較少用)
3.png
示例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);
}