block的使用場景
1.把block保存到對象中,恰當(dāng)時機(jī)的時候才去調(diào)用
2.把block當(dāng)做方法的參數(shù)使用,外界不調(diào)用,都是方法內(nèi)部去調(diào)用,Block實現(xiàn)交給外界決定.
3.把block當(dāng)做方法的返回值,目的就是為了代替方法.,block交給內(nèi)部實現(xiàn),外界不需要知道Block怎么實現(xiàn),只管調(diào)用
ViewController.m文件
@interface ViewController ()
@property(nonatomic,strong)Person *p;
@end
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
[self block1];
[self block2];
[self block3];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
_p.blockName();
}
-(void)block1{
Person *p = [[Person alloc] init];
// 賦值
void(^blockname)() = ^() {
NSLog(@"執(zhí)行對象中的block");
};
p.blockName = blockname;
// 賦值
p.blockName = ^(){
NSLog(@"執(zhí)行對象中的block");
};
_p = p;
}
-(void)block2{
Person *p = [[Person alloc] init];
[p eat:^{
NSLog(@"block作為函數(shù)參數(shù)");
}];
}
-(void)block3{
Person *p = [[Person alloc] init];
p.eat(@"block作為返回值");
}
Person.h
@property (nonatomic ,strong) void(^blockName)();
-(void)eat:(void(^)())block;
-(void(^)(NSString *))eat;
Person.m
-(void)eat:(void (^)())block{
// 執(zhí)行block
block();
}
-(void (^)(NSString *))eat{
// 返回block
return ^(NSString * name){
NSLog(@"%@---",name);
};
}
實際應(yīng)用
封裝try—catch塊:
+ (void)tryCatchViewControll:(UIViewController *)VC function:(void (^)(void))function{
@try {
function();
} @catch (NSException *exception) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
message:@"出錯了龙誊!"
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"確定"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
}]];
[VC presentViewController:alertController animated:YES completion:^{}];
} @finally {
}
}