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  。

原文地址:https://www.cnblogs.com/sjxjjx/p/6515951.html