main.m
//
// main.m
// 05-協議代理的作用(傳值)
//
// Created by 余婷 on 16/3/28.
// Copyright (c) 2016年 余婷. All rights reserved.
//
//場景:上一級界面顯示下一級界面的內容
//分析:下一級界面想要將自己的內容顯示在上一級界面,但是自己做不到,需要上一級界面來幫他完成
//三要素:
//委托:下一級界面(綠色界面)
//協議:顯示指定的內容
//代理:上一級界面(黃色界面)
//使用協議代理完成傳值:協議方法帶參數(委托將要傳的值,通過協議方法的參數傳給代理)
#import <Foundation/Foundation.h>
#import "YTYellowView.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//1.創建黃色界面(代理)
YTYellowView * yellow = [[YTYellowView alloc] init];
//2.創建綠色界面 (委托)
YTGreenView * green = [[YTGreenView alloc] init];
//3.設置代理
green.delegate = yellow;
//顯示輸入內容
char a[100];
scanf("%s", a);
[green showData:[NSString stringWithUTF8String:a]];
}
return 0;
}
YTYellowView.h
#import <Foundation/Foundation.h>
#import "YTGreenView.h"
//遵守協議,實現協議方法
@interface YTYellowView : NSObject <SendDataDelegate>
@end
YTYellowView.m
#import "YTYellowView.h"
@implementation YTYellowView
//實現協議方法,打印指定內容
- (void)show:(NSString *)str{
NSLog(@"顯示:%@", str);
}
@end
YTGreenView.h
#import <Foundation/Foundation.h>
//2.協議
@protocol SendDataDelegate <NSObject>
//讓協議方法帶參來實現傳值
- (void)show:(NSString *)str;
@end
//1.委托
@interface YTGreenView : NSObject
//需要代理
@property(nonatomic, weak) id<SendDataDelegate> delegate;
//告訴代理去顯示指定的數據
- (void)showData:(NSString *)myStr;
@end
YTGreenView.m
#import "YTGreenView.h"
@implementation YTGreenView
- (void)showData:(NSString *)myStr{
//判斷代理是否實現了協議方法
if ([self.delegate respondsToSelector:@selector(show:)]) {
[self.delegate show:myStr];
}
}
@end