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

  • 相关阅读:
    tar.gz文件
    Ruby Symbol
    Ruby表达式
    Linux相关命令
    Ruby file
    Tomcat优化
    修改Linux文件的所属用户和组
    Ruby String
    Ruby Range
    HTML5开源专业图像处理引擎——AlloyImage(简称AI)
  • 原文地址:https://www.cnblogs.com/zhang-kiwi/p/5024981.html
Copyright © 2011-2022 走看看