//
// 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];
//將代理人設(shè)置成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>
//保姆的協(xié)議
@protocol NannyDelegate <NSObject>
- (void)washClothes;
- (void)cook;
@optional
- (void)takeCareBaby;
@end
@interface Boss : NSObject
//代理屬性要用assign或weak去修飾,不需要使用OC中的內(nèi)存管理方式
@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>
//保姆的協(xié)議
@protocol NannyDelegate <NSObject>
- (void)washClothes;
- (void)cook;
@optional
- (void)takeCareBaby;
@end
@interface Boss : NSObject
//代理屬性要用assign或weak去修飾,不需要使用OC中的內(nèi)存管理方式
@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(@"去上班");
//判斷代理人能否實(shí)現(xiàn)某個方法
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> //簽署協(xié)議
@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
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。