delegate - 代理基础- 02

2020-07-23  本文已影响0人  js_huh

delegate-代理基础01


是什么?


示例代码

-- 协议
#import <Foundation/Foundation.h>
@protocol ConveyProtocol <NSObject>
-(NSString *)sendThing:(NSString *)thingName; //传递物品,接收反馈
@end
-- 委托方
#import "ConveyProtocol.h"
@interface Chef : NSObject
@property(nonatomic,weak)id <ConveyProtocol> delegate; //设置代理属性
-(void)sendFood; //传菜
@end

@implementation Chef
-(void)sendFood{
  NSLog(@"快来传菜...");
  if ([self.delegate respondsToSelector:@selector(sendThing:)]) {
  NSString* info = [self.delegate sendThing:@"辣子鸡丁"];
  NSLog(@"味道如何?%@",info);
  }
}
@end
-- 代理方
#import "ConveyProtocol.h"
@interface Waiter : NSObject <ConveyProtocol>
@end

@implementation Waiter
- (NSString *)sendThing:(NSString *)thingName {
    NSLog(@"服务员把'%@'端上去",thingName);
    NSString * evaluateInfo =[NSString stringWithFormat:@"顾客反馈说,%@太好吃了,真棒!",thingName];
    //@"太好吃了,真棒!";
    return evaluateInfo;
}
-- 使用代理
- (void)viewDidLoad {
    [super viewDidLoad];
    Waiter * wa = [[Waiter alloc]init];
    Chef * cf = [[Chef alloc]init];
    cf.delegate = wa;
    [cf sendFood];
}

注意:


也可以看看


来自于哪里?


上一篇下一篇

猜你喜欢

热点阅读