iOS-Block

作者: 存在即是美 | 来源:发表于2017-01-17 10:35 被阅读5次

    block已经成为我在iOS编写中最为常用的回调方法 , 它简单便捷 , 取代了代理大部分的工作 , 今天整理一下 , 只需要跟着敲一遍就会了 , 如果学过C的话 , 对照函数 , 把*变成^就差不多了 .

    void(^myblocks)(void) = NULL;
    myblocks = ^(void){
       NSLog(@"in myblocks");
    };
    NSLog(@"before myblocks");
    myblocks();
    NSLog(@"after myblocks");
    
    
    int (^myblocks2)(int a,int b) = NULL;
    myblocks2 = ^(int a, int b){
        int c = a + b;
        return c;
    };
    NSLog(@"before myblock2");
    int ret = myblocks2(10 , 23);
    NSLog(@"after myblock2 %d",ret);
    
    
    //这个需要注意
    __block int sum = 0;
    int (^myblocks3) (int a , int b) = ^(int a , int b){
        sum = a + b;
        return 3;
    };
    int ret2 = myblocks3(33 , 77);
    NSLog(@"%d",ret2);
    NSLog(@"%d",sum);
    
    //typedef
    myblock4 mybl = ^(void){
        NSLog(@"typedef 的调用");
    };
    mybl();
    

    下面是常用方式:
    在建立的一个view中写一个block然后在控制器中调用:

    1.创建view
    .h中
    #import <UIKit/UIKit.h>
    typedef void (^myblocksMB)(void);
    @interface ButtonView : UIView
    @property (nonatomic , copy) myblocksMB blockMB;
    @end

    .m中
    #import "ButtonView.h"

    @implementation ButtonView
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
    if (self = [super initWithFrame:frame]) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor redColor];
        
        button.frame = CGRectMake(0, 0, frame.size.width/2, frame.size.width/2);
        
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:button];
    }
    
        return self;
    }
    
    - (void)buttonClick:(UIButton *)button
    {
        if (self.blockMB) {
            self.blockMB();
        }
    }
    @end
    

    2.控制器中调用

    #import "ViewController.h"
    #import "ButtonView.h"
    @interface ViewController ()
    end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        ButtonView *view = [[ButtonView alloc] initWithFrame:CGRectMake(100, 100, 100, 300)];
    
        [self.view addSubview:view];
    
        view.blockMB = ^(void){
    
            NSLog(@"回调的方法");
    
        };
    }
    @end
    

    点击红色小方块就可以打印"回调的方法"了.可以带参数 , 跟上面区别不大,把void换一下就好了 .还有一个 , 很多时候 , 例如在封装网络请求的时候 , 把block当参数拼进去 , 就把(void)(^block)(void)看做一个整体 , 看做NSString之类的就可以了 , 例如很多人现在用的AFNetworking里面就有 , 可以跟着敲两遍 , 用时间长了 , 就自然了 .

    相关文章

      网友评论

          本文标题:iOS-Block

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