1. block帮你保存一份代码,等到恰当的时候调用
void(^block)(int) = ^(int reuslt){
NSLog(@"%d",reuslt);
};
block(2);
2.保存在对象中,恰当的时候才去调用
#import "Person.h"
@property (nonatomic,strong)void(^operation)();
Person *p = [[Person alloc]init];
void(^block)() = ^() {
NSLog(@"执行对象中block");
};
p.operation = block;
p.operation();
3.把block当做方法的的参数,外界不调用,都是方法的内部调用
#import "Person.h"
-(void)eat:(void (^)())block;
#import "Person.m"
-(void)eat:(void (^)())block
{
// 方法的内部调用
block();
}
4.把block当做方法的返回值
#import "Person.h"
-(void (^)(int))run;
#import "Person.m"
-(void (^)(int))run
{
return ^(int metre){
NSLog(@"跑了%d米",metre);
};
}
#import "ViewController.h"
Person *p = [[Person alloc]init];
p.run(2);
网友评论