zoukankan      html  css  js  c++  java
  • iOS-设计模式之Block

    Block是代码块,

    Block定义

    返回值 (^ 块名)(参数1,参数2…);

    在定义Block的时候可以使用typedef 重命名一下。

    typedef void(^blockName)(NSString *string);

    Block和函数的相似性:

    (1)可以保存代码

    (2)有返回值

    (3)有形参

    (4)调用方式一样。

    具体实现过程:

    //  SecondViewController.h
    #import <UIKit/UIKit.h>
    
    typedef void(^blockName)(NSString *string);
    
    @interface SecondViewController : UIViewController
    
    @property (nonatomic, copy)blockName sendBlock;
    
    @end
    
    
    //  SecondViewController.m
    - (IBAction)actionTow:(id)sender {
        self.sendBlock(self.textfile.text);
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    
    
    //  ViewController.m
    #import "ViewController.h"
    #import "SecondViewController.h"
    
    @interface ViewController ()
    @property (weak, nonatomic) IBOutlet UILabel *lable;
    @property (strong, nonatomic)SecondViewController *secondVC;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        self.secondVC = [[SecondViewController alloc]init];
    //    ARC情况下解决循环引用的方式: _weak
        __weak ViewController *weakThis = self;
        self.secondVC.sendBlock = ^(NSString *string){
    //        如果要访问属性 还要使用__strong 来修饰。
            __strong ViewController *strongThis = weakThis;
            strongThis.lable.text = string;
        };
    }
    - (IBAction)actionOne:(id)sender {
        [self presentViewController:self.secondVC animated:YES completion:nil];
    }

    本文GitHub地址https://github.com/zhangkiwi/iOS_SN_Block

  • 相关阅读:
    Asp.Net 获取客户端真实IP方法总结
    C# 中英文符号互转(半角全角互转)
    执行git commit命令提示: “Please tell me who you are”的解决方案
    Tools
    VSC
    DevOps
    VSC
    DevOps
    DevOps
    K8S
  • 原文地址:https://www.cnblogs.com/zhang-kiwi/p/5024981.html
Copyright © 2011-2022 走看看