block的简单使用

作者: 芝麻绿豆 | 来源:发表于2015-10-25 22:30 被阅读191次

    block的使用场景

    1.把block保存到对象中,恰当时机的时候才去调用
    2.把block当做方法的参数使用,外界不调用,都是方法内部去调用,Block实现交给外界决定.
    3.把block当做方法的返回值,目的就是为了代替方法.,block交给内部实现,外界不需要知道Block怎么实现,只管调用

    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(@"执行对象中的block");
        };
        p.blockName = blockname;
        // 赋值
        p.blockName = ^(){
            NSLog(@"执行对象中的block");
        };
        _p = p;
    }
    -(void)block2{
        Person *p = [[Person alloc] init];
        [p eat:^{
            NSLog(@"block作为函数参数");
        }];
    }
    -(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{
        // 执行block
        block();
    }
    -(void (^)(NSString *))eat{
        // 返回block
        return ^(NSString * name){
            NSLog(@"%@---",name);
        };
    }
    

    实际应用

    封装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 {
            
        }
    }
    

    相关文章

      网友评论

        本文标题:block的简单使用

        本文链接:https://www.haomeiwen.com/subject/obcxhttx.html