美文网首页
block--闭包 的分析使用

block--闭包 的分析使用

作者: KevinChein | 来源:发表于2017-10-16 13:40 被阅读21次

    1.object-C中的block

      1. 作用:保存一段代码块

    • 2.声明
      block的写法:

      block的写法: 类型: 返回值类型(^block的名称)(block的参数)
      值: ^(参数列表) {
      // 执行的代码
      }
      //例子 
      int (^sumOfNumbers)(int a, int b) = ^(int a, int b) { return a + b; };
      

    • 3.定义
      block的定义有三种方式
      // block定义的三种方式

        // 方式一
            void(^block1)() = ^(){
        
        };
        // 方式二 如果没有参数,参数可以隐藏,如果有参数,定义的时候必须写参数,而且必须要有参数变量名
        void(^block2)() = ^{
        
        };
        void(^block2_1)(int) = ^(int a){//这里的参数a不能省略,因为下面的代码块要用到这个参数 
            
        };
        void(^block2_2)(int a) = ^(int a){
            
        };
      
        // 方式三 block的返回是可以省略的,不管有没有返回值都可以省略
        int (^block3)() = ^int{
            return 0;
        };
        int (^block3_1)() = ^{
            return 0;
        };
      

    • 4.类型

        // 2.block的定义:int(^)(NSString *)<----这就是block的声明
        int(^block4)(NSString *) = ^(NSString *str){
            return 1;
        };
        
        block1();//block的调用
        //inLineBlock:快速创建一个block的快捷方式,如下
        <#returnType#>(^<#blockName#>)(<#parameterTypes#>) = ^(<#parameters#>) {
            <#statements#>
        };
      

    2.block在开发中的使用场景

    • 1.场景一 (基本没有实际意义)
      目的:在一个方法中定义了代码块,可以在另一个方法中去使用;此种方法和直接写一个方法等价,没多大意义。
      #import "ViewController.h"

        // BlockName:block类型别名
        typedef void(^BlockName)();
      
        @interface ViewController ()
      
        // block怎么声明就怎么定义属性
        // 方式一 : 直接用block声明,block如何声明就如何定义成属性
        @property (nonatomic,strong) void(^block)();
        // 方式二 : 给block起别名,用别名作为类型
        @property (nonatomic,strong) BlockName block1;
      
        @end
      
        @implementation ViewController
      
        - (void)viewDidLoad {
            [super viewDidLoad];
            
            void(^block)() = ^{
                NSLog(@"直接用block声明的block   调用了block");
            };
            
            void(^blockName)() = ^{
                NSLog(@"使用block起别名的方式   调用了block");
            };
            
            _block = block;
            _block1 = blockName;
      
        }
        - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
            // 调用block
            _block1();
            _block();
        }
      
       打印输出结果:
       1.使用block起别名的方式   调用了block
       2.直接用block声明的block   调用了block
      

    • 2.场景二 (应用最多)
      目的:在一个类中定义, 在另外一个类中去使用
      #import <Foundation/Foundation.h>

        @interface CellItem : NSObject
        @property (nonatomic, copy) NSString *title;
      
        @property (nonatomic, strong) void(^block)(); // 作为属性保存到这个模型中
      
        + (instancetype)itemWithTitle:(NSString *)title;
        @end
        #import "CellItem.h"
      
        @implementation CellItem
      
        + (instancetype)itemWithTitle:(NSString *)title {
            CellItem *item = [[self alloc] init];
            item.title = title;
            return item;
        }
        @end
      

        #import "ViewController.h"
        #import "CellItem.h"
    
        @interface ViewController ()
    
        @property (nonatomic, strong) NSArray *itemArray;
    
        @end
    
        @implementation ViewController
    
        - (void)viewDidLoad {
            [super viewDidLoad];
            
            // 初始化tableView
            _myTableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
            _myTableView.delegate = self;
            _myTableView.dataSource = self;
            [self.view addSubview:_myTableView];
            
            CellItem *item1 = [CellItem itemWithTitle:@"打电话"];
            item1.block = ^{
                NSLog(@"调用打电话功能");
            };
            
            CellItem *item2 = [CellItem itemWithTitle:@"发短信"];
            item2.block = ^{
                NSLog(@"调用发短信功能");
            };
    
            CellItem *item3 = [CellItem itemWithTitle:@"发邮件"];
            item3.block = ^{
                NSLog(@"调用发邮件功能");
            };
    
            _itemArray = @[item1,item2,item3];
        }
    
    
    
        - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
            return _itemArray.count;
        }
    
    
        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
            static NSString *ID = @"cell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
            }
            // 此处如果不用数组就必须使用大量的ifelse语句
            CellItem *item = self.itemArray[indexPath.row];
            cell.textLabel.text = item.title;
            return cell;
        }
    
    
        - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
            CellItem *item = self.itemArray[indexPath.row];
            // 此处如果不用数组就必须使用大量的ifelse语句
            if (item.block) {// 必须要判断下block是否有值
                item.block();
            }  
        }
    
    • 3.场景三
      目的:使用block去传值,可与delegate互换。(数据的逆向传递)

       #pragma mark
       这里ModaViewController想把一个字符串传递给ViewController,
       于是ModaViewController就需要拿到ViewController,
       那么就要在ModaViewController中写一个代理,
       让ViewController去实现这个代理;
      
        #import <UIKit/UIKit.h>
      
        //@class ModaViewController;
        //
        //@protocol ModaViewControllerDelegate <NSObject>
        //@optional
        //// 设计需要实现的方法: 想要代理做什么事情就怎么去设计
        //// 什么时候实现代理?---> 这里就简单的定义为当点击屏幕的时候就将value值传递过去
        //- (void)modaViewController:(ModaViewController *)vc sendValue:(NSString *)value;
        //@end
      
        @interface ModaViewController : UIViewController
        // 用block替换下面的代理--哪里用代理,哪里就可以用block去替换
        @property (nonatomic, strong) void(^block)(NSString *value); // <---value是block的传入参数
      
        //@property (nonatomic, weak) id<ModaViewControllerDelegate> myDelegate;
        @end
        --------------------------------------------------------------
        #import "ModaViewController.h"
      
        @interface ModaViewController ()
      
        @end
      
        @implementation ModaViewController
      
        - (void)viewDidLoad {
            [super viewDidLoad];
            // Do any additional setup after loading the view.
            self.view.backgroundColor = [UIColor blueColor];
        }
      
        - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
            // 传值给ViewController
        //    if ([_myDelegate respondsToSelector:@selector(modaViewController:sendValue:)]) { // 查看这个代理是否有需要实现的方法
        //        // 如果有需要实现的方法就让代理直接去实现
        //        [_myDelegate modaViewController:self sendValue:@"123456"];
        //    }
            if (_block) {
                _block(@"123456");
            }
            
        }
        @end
          --------------------------------------------------------------
        #import "ViewController.h"
        #import "ModaViewController.h"
      
        @interface ViewController () //<ModaViewControllerDelegate>
      
        @end
        
        @implementation ViewController
      
        - (void)viewDidLoad {
            [super viewDidLoad];
            // Do any additional setup after loading the view, typically from a nib.
        }
      
        - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
            
            // 推出控制器
            ModaViewController *modaVC = [ModaViewController new];
            [self presentViewController:modaVC animated:YES completion:nil];
            
            // 在这里需要ViewController控制器拿到ModaViewController的代理方法,代理并实现拿到的代理方法
        //    modaVC.myDelegate = self;
            
            modaVC.block = ^(NSString *value) {
                NSLog(@"打印block传过来的值  == %@", value);
            };
            
        }
      
        #pragma mark ModaViewController---myDelegate
        //- (void)modaViewController:(ModaViewController *)vc sendValue:(NSString *)value {
        //    NSLog(@"打印代理传过来的值  == %@", value);
        //}
        @end
      
    屏幕快照 2017-10-17 下午3.12.06.png 屏幕快照 2017-10-17 下午3.12.31.png 屏幕快照 2017-10-17 下午3.13.13.png
    • 4.block作为参数进行延时回调
      定义网络请求的类

      @interface HttpTool : NSObject 
      -(void)loadRequest:(void (^)())callBackBlock; 
      @end 
      @implementation HttpTool 
      -(void)loadRequest:(void (^)())callBackBlock {         
           dispatch_async(dispatch_get_global_queue(0, 0), ^{ 
                NSLog(@"异步延时请求操作在这里,加载网络数据:%@", [NSThread currentThread]);
                dispatch_async(dispatch_get_main_queue(), ^{
                          callBackBlock(); 
                 }); 
           }); 
      }          
      @end
      

      进行网络请求,请求到数据后利用block进行回调

      -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        [self.httpTool loadRequest:^{
            NSLog(@"主线程中,将数据回调.%@", [NSThread currentThread]);
        }];
      }
      

    Swift中的闭包

    <1>. 闭包写法总结:

    类型:(形参列表)->(返回值)
    技巧:初学者定义闭包类型,直接写()->().再填充参数和返回值
    
    值:
    {
        (形参) -> 返回值类型 in
        // 执行代码
    }
    
    let b = { (parm : Int) -> (Int) in 
       print(parm)
    }
    
    //调用
    b(100)
    

    <2>.闭包的简写

    如果闭包没有参数,没有返回值,in和in之前的内容可以省略
    
      httpTool.loadRequest({
          print("回到主线程", NSThread.currentThread());
      })
    
    尾随闭包写法:
        如果闭包是函数的最后一个参数,则可以将闭包写在()后面
    
        如果函数只有一个参数,并且这个参数是闭包,那么()可以不写
    
        httpTool.loadRequest() {
            print("回到主线程", NSThread.currentThread());
        }
    
        // 开发中建议该写法
        httpTool.loadRequest {
            print("回到主线程", NSThread.currentThread());
        }
    

    <3>.使用闭包代替block,闭包作为参数进行延时回调

    定义网络请求的类
    
    class HttpTool: NSObject {
      func loadRequest(callBack : ()->()){
          dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
              print("加载数据", [NSThread.currentThread()])
    
               dispatch_async(dispatch_get_main_queue(), { () -> Void in
                  callBack()
               })
          }
      }
    }
    
    进行网络请求,请求到数据后利用闭包进行回调
    
      override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
          // 网络请求
          httpTool.loadRequest ({ () -> () in
              print("回到主线程", NSThread.currentThread());
          })
      }
    

    <3>.实例二,闭包的回调传值

    //[weak self]:解决循环引用导致的内存泄露
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        delayMethod {[weak self] (re) ->() in
            print("$$$$$$$$$$$$$$$$$:\(re)%%%%%%%%%%%\(String(describing: self))")
        }
        delayMethod(comletion: {[weak self] (re)->() in
            print("********:\(re)*************\(String(describing: self))")
        })
    }
    
    //@escaping:逃逸闭包。它的定义非常简单而且易于理解。如果一个闭包被作为一个参数传递给一个函数,并且在函数return之后才被唤起执行,那么这个闭包是逃逸闭包。
    func delayMethod(comletion: @escaping (_ results: String,_ resultss:String) -> ()) ->(){
        //开启一个全局异步子线程
        DispatchQueue.global().async {
            Thread.sleep(forTimeInterval: 2.0)
            //回调到主线程
            DispatchQueue.main.async(execute: {
                print("主线程更新 UI \(Thread.current)")
                comletion("qwertyui","asdf")
            })
        }
    }
    

    <4>.闭包进行两个界面的传值

    我们要实现点击第二个界面后,关掉第二个界面,并且传值给第一个界面
    <1>.首先在第二个界面声明闭包进行操作
    
    class NewViewController: UIViewController {
      //声明闭包
      typealias lewisCloser = (_ paramOne : String? ) -> ()
      //定义个变量 类型就是上面声明的闭包
      var customeCloser: lewisCloser?
      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
          if(customeCloser != nil) {
              customeCloser!("要发给第一个界面的值")
          }
          self.dismiss(animated: true, completion: nil)
      }
      override func viewDidLoad() {
          super.viewDidLoad()
          // Do any additional setup after loading the view.
      }
    }
    
    <2>.在第一个界面实现闭包,取得要穿的值
    
    let vc = NewViewController()
    //实现闭包
    vc.customeCloser = {(cusValue) -> () in
        //cusValue就是传过来的值
        print("^^^^^^^^^^^^^^^^^^^^^:\(cusValue!)")
    }
    self.present(vc, animated: true, completion: nil)
    

    关于Swift许多部分我自己也是一知半解,这篇文章完全是为自学加深记忆。如有发现错误烦请指正~~~
    闭包部分完全抄袭:LewisZhu,抱歉!!! 大家也可移步至下方原著链接🔗
    作者:LewisZhu
    链接:http://www.jianshu.com/p/1457a4894ec7

    相关文章

      网友评论

          本文标题: block--闭包 的分析使用

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