OC协议代理的反向传值作用

FJSecondView.h

#import <Foundation/Foundation.h>

@protocol sendDataDelegate <NSObject>

//1.协议;

//就在协议方法中带参数实现传值的功能

- (void) showTheContents:(NSString *)string;


@end



//2.委托

@interface FJSecondView : NSObject

//需要一个代理

@property (nonatomic,weak) id <sendDataDelegate> delegate;

//需要告诉代理什么时候显示自己输入的内容;

- (void) toShowMyData:(NSString *) myString;



@end

FJSecondView.m

#import "FJSecondView.h"


@implementation FJSecondView


- (void) toShowMyData:(NSString *)myString{

    

    if ([_delegate respondsToSelector:@selector(showTheContents:)]) {

        

        [_delegate showTheContents:myString];

        

    }

    

}


@end

FJFirstView.h

#import <Foundation/Foundation.h>

#import "FJSecondView.h"


@interface FJFirstView : NSObject <sendDataDelegate>



@end


FJFirstView.m

#import "FJFirstView.h"


@implementation FJFirstView


- (void)showTheContents:(NSString *)string{

    

    NSLog(@"第一页显示第二页的内容:%@",string);

}

@end


main.m

//使用协议代理完成传值:协议方法带参数;

//委托将要传的值通过协议方法的参数传给代理


//场景:上一级界面显示下一级界面的内容

//分析:下一集界面想要自己的内容显示到上一级界面但是自己做不到

//需要上一级帮他完成


//三要素:

//委托:下一级界面

//协议:显示指定的内容

//代理:上一级界面

#import <Foundation/Foundation.h>

#import "FJFirstView.h"

int main(int argc, const char * argv[]) {

    @autoreleasepool {

        //1.创建代理

        FJFirstView *first = [[FJFirstView alloc]init];

        //2.创建委托

        FJSecondView *second = [[FJSecondView alloc]init];

        //3.设置代理

        second.delegate = first;

        //4.完成协议内容

        char a[100];

        scanf("%s",a);

        [second toShowMyData:[NSString stringWithUTF8String:a]];

        

    }

    return 0;

}


你可能感兴趣的:(OC反向传值)