//
// main.m
// OC_代理
//
// Created by lanou3g on 17/8/2.
// Copyright © 2017年 lanou3g. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Boss.h"
#import "Worker.h"
int main(int argc, const char * argv[]) {
Boss *boss = [[Boss alloc] init];
Worker *worker = [[Worker alloc] init];
//将代理人设置成worker
boss.delegate = worker;
[boss hungry];
[boss clothesDirty];
[boss working];
return 0;
}
//
// Boss.h
// OC_代理
//
// Created by lanou3g on 17/8/2.
// Copyright © 2017年 lanou3g. All rights reserved.
//
#import <Foundation/Foundation.h>
//保姆的协议
@protocol NannyDelegate <NSObject>
- (void)washClothes;
- (void)cook;
@optional
- (void)takeCareBaby;
@end
@interface Boss : NSObject
//代理属性要用assign或weak去修饰,不需要使用OC中的内存管理方式
@property (nonatomic, assign) id<NannyDelegate>delegate;
- (void)clothesDirty;
- (void)hungry;
- (void)working;
@end
//
// Boss.h
// OC_代理
//
// Created by lanou3g on 17/8/2.
// Copyright © 2017年 lanou3g. All rights reserved.
//
#import <Foundation/Foundation.h>
//保姆的协议
@protocol NannyDelegate <NSObject>
- (void)washClothes;
- (void)cook;
@optional
- (void)takeCareBaby;
@end
@interface Boss : NSObject
//代理属性要用assign或weak去修饰,不需要使用OC中的内存管理方式
@property (nonatomic, assign) id<NannyDelegate>delegate;
- (void)clothesDirty;
- (void)hungry;
- (void)working;
@end
//
// Boss.m
// OC_代理
//
// Created by lanou3g on 17/8/2.
// Copyright © 2017年 lanou3g. All rights reserved.
//
#import "Boss.h"
@implementation Boss
- (void)clothesDirty {
NSLog(@"本老板的衣服脏了");
[self.delegate washClothes];
}
- (void)hungry {
NSLog(@"本大王饿了");
[self.delegate cook];
}
- (void)working {
NSLog(@"去上班");
//判断代理人能否实现某个方法
if ([self.delegate respondsToSelector:@selector(takeCareBaby)]) {
[self.delegate takeCareBaby];
}else {
NSLog(@"带着孩子去上班");
}
}
@end
//
// Worker.h
// OC_代理
//
// Created by lanou3g on 17/8/2.
// Copyright © 2017年 lanou3g. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Boss.h"
@interface Worker : NSObject<NannyDelegate> //签署协议
@end
//
// Worker.m
// OC_代理
//
// Created by lanou3g on 17/8/2.
// Copyright © 2017年 lanou3g. All rights reserved.
//
#import "Worker.h"
@implementation Worker
- (void)washClothes {
NSLog(@"洗刷刷");
}
- (void)cook {
NSLog(@"making");
}
- (void)takeCareBaby {
NSLog(@"保姆带孩子");
}
@end