参考:https://www.zhihu.com/question/33498315?sort=created
- SecDelegate.h
#import <Foundation/Foundation.h>
@protocol SecDelegate <NSObject>
// 发邮件
@optional
-(void)sendMail;
// 发工资
@required
-(void)payoff;
// 接电话
@required
-(void)tel;
@end
- Sec.h
定义接口Sec,并遵守协议SecDelegate
#import <Foundation/Foundation.h>
#import "SecDelegate.h"
@interface Sec : NSObject <SecDelegate>
@end
- Sec.m
Sec接口实现
#import "Sec.h"
@implementation Sec
-(id)init{
self = [super init];
if (self) {
//
}
return self;
}
-(void)payoff{
NSLog(@"发工资");
}
-(void)tel{
NSLog(@"打电话");
}
@end
- Boss.h
定义Boss接口,并定义外部访问的实例方法
#import "SecDelegate.h"
@interface Boss : NSObject
// id对象的指针,遵守协议SecDelegate
@property(nonatomic,retain)id<SecDelegate>delegate ;
// 管理
-(void)manage;
// 教导新员工
-(void)teach;
-(void)payoff;
-(void)tel;
@end
- Boss.m
Boss的接口实例,注意要遵守协议SecDelegate
#import "Boss.h"
// 类扩展
@interface Boss ()<SecDelegate>
@end
@implementation Boss
@synthesize delegate = _delegate;
// @synthesize delegate;
-(id)init{
self = [super init];
if (self) {
//
}
return self;
}
-(void)manage{
NSLog(@"管理");
}
-(void)teach{
NSLog(@"教导新员工");
}
-(void)payoff{
// ARC 模式不需要 NSAutoreleasePool
// NSAutoreleasePool *p=[[NSAutoreleasePool alloc] init];
[self.delegate payoff];
// [p release];
NSLog(@"发完工资了吗");
}
-(void)tel{
[_delegate tel];
}
@end
- 调用
// 实例化老板对象
Boss *boss = [[Boss alloc] init];
// 实例化秘书对象
Sec *sec = [[Sec alloc] init];
boss.delegate = sec;
[boss manage];
[boss teach];
[boss tel];
[boss payoff];