一、协议(protocol)

参考:https://www.zhihu.com/question/33498315?sort=created

  1. SecDelegate.h
#import 
@protocol SecDelegate 
// 发邮件
@optional
-(void)sendMail;
// 发工资
@required
-(void)payoff;
// 接电话
@required
-(void)tel;
@end
  1. Sec.h
    定义接口Sec,并遵守协议SecDelegate
#import 
#import "SecDelegate.h"
@interface Sec : NSObject 
@end
  1. Sec.m
    Sec接口实现
#import "Sec.h"
@implementation Sec
-(id)init{
    self = [super init];
    if (self) {
        //
    }
    return self;
}
-(void)payoff{
    NSLog(@"发工资");
}
-(void)tel{
    NSLog(@"打电话");
}
@end
  1. Boss.h
    定义Boss接口,并定义外部访问的实例方法
#import "SecDelegate.h"
@interface Boss : NSObject
// id对象的指针,遵守协议SecDelegate
@property(nonatomic,retain)iddelegate ;
// 管理
-(void)manage;
// 教导新员工
-(void)teach;
-(void)payoff;
-(void)tel;
@end
  1. Boss.m
    Boss的接口实例,注意要遵守协议SecDelegate
#import "Boss.h"
// 类扩展
@interface Boss ()
@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
  1. 调用
    // 实例化老板对象
    Boss *boss = [[Boss alloc] init];
    // 实例化秘书对象
    Sec *sec = [[Sec alloc] init];
    boss.delegate = sec;
    [boss manage];
    [boss teach];
    [boss tel];
    [boss payoff];

你可能感兴趣的:(一、协议(protocol))