• iOS基础之顺传逆传传值(delegate、block)


            写给iOS新手的福利!

            在项目中经常会用到传值,根据传值的方向分为顺传(从根控制器到子控制器)和逆传(从子控制器到根控制器)。在这里写了个Demo简单演示了效果,创建了两个控制器:

    一个为根控制器,一个为子控制器。

            顺传:这种传值方式最为简单,在子控制器中添加一个属性即可。

            下面是OtherViewController.h文件

    #import <UIKit/UIKit.h>
    
    @interface OtherViewController : UIViewController
    
    /** 顺传数据 */
    @property(nonatomic, copy) NSString *pushString;
    
    @end

            在根控制器中,跳转时设置传入值

        OtherViewController *otherVC = [[OtherViewController alloc] init];
        otherVC.pushString = @"从根控制器传入的字符串";
        [self.navigationController pushViewController:otherVC animated:YES];

            这样就可以在子控制器中获取传入值。

            逆传(delegate方式):

            下面是OtherViewController.h文件,添加协议方法和代理。

    #import <UIKit/UIKit.h>
    
    @protocol OtherViewControllerDelegate <NSObject>
    
    - (void)popVCWithString:(NSString *)popString;
    
    @end
    
    @interface OtherViewController : UIViewController
    
    /** 代理 */
    @property(nonatomic, weak) id<OtherViewControllerDelegate> delegate;
    
    @end

            在需要传值的时候,使用以下代码传出需要传的值:

    if ([self.delegate respondsToSelector:@selector(popVCWithString:)]) {
            [self.delegate popVCWithString:@"通过代理从子控制器传回的字符串"];
        }

            这个时候需要在根控制器(ViewController.m)中进行设置了,设置代理:

        OtherViewController *otherVC = [[OtherViewController alloc] init];
        // 设置代理
        otherVC.delegate = self;
        [self.navigationController pushViewController:otherVC animated:YES];

            遵守代理协议:

    // 遵守代理协议
    @interface ViewController ()<OtherViewControllerDelegate>

            实现代理方法:

    // 代理方法
    - (void)popVCWithString:(NSString *)popString
    {
        // 在这里获取逆传的值
        NSLog(@"popString ----- %@", popString);
    }

            逆传(block方式):

            在子控制器(OtherViewController.h)中声明Block,添加Block属性

    #import <UIKit/UIKit.h>
    
    typedef void(^PopStringBlock)(NSString *popString);
    
    @interface OtherViewController : UIViewController
    
    /** Block */
    @property(nonatomic, copy) PopStringBlock popBlock;
    
    @end

            在需要传值的时候,使用以下代码传出需要传的值:

    self.popBlock(@"通过Block从子控制器传回的字符串");

            这个时候只需要在根控制器(ViewController.m)中需要取值的地方调用Block即可:

        OtherViewController *otherVC = [[OtherViewController alloc] init];
        otherVC.popBlock = ^(NSString *popString) {
            // 获取Block方式逆传的值
            NSLog(@"popString ----- %@", popString);
        };
        [self.navigationController pushViewController:otherVC animated:YES];

            写的比较简单,关键地方都附上代码了,不明白的可以去看我的Demo:  https://github.com/sjxjjx/Delegate_Block  。

  • 相关阅读:
    .Net利用core实现简单的加解密例程全解析
    HTTPS抓包,利用telnet检查网络连接的几种方式
    每个人都应该知道的(cJSON)JSON处理库
    HashMap和Hashtable的区别
    Map集合
    Set集合
    同步异步以及泛型
    ArrayList的输出方式以及因子增长数
    (转)C++内存分配方式详解——堆、栈、自由存储区、全局/静态存储区和常量存储区
    数据结构复习---最短路径
  • 原文地址:https://www.cnblogs.com/sjxjjx/p/6515951.html
Copyright © 2020-2023  润新知