协议

接口文件1:Hunter.h

#import <Foundation/Foundation.h>
#import "TProtocol.h"

@interface Hunter : NSObject
@property (nonatomic,retain) id <TProtocol> animal;
- (void) hunt;

@end



实现文件1:Hunter.m

#import "Hunter.h"
#import "TProtocol.h"

@implementation Hunter
- (void) hunt
{
    if (_animal != nil)
    {
        [_animal catched];
    }
    if (_animal != nil && [_animal respondsToSelector:@selector(escape)])
    {
         [_animal escape];
    }
}
@end



接口文件2:Tiger.h

#import <Foundation/Foundation.h>
#import "TProtocol.h"

@interface Tiger : NSObject <TProtocol>
//- (void) catched;
//- (void) escape;

@end

实现文件2:Tiger.m

#import "Tiger.h"

@implementation Tiger : NSObject
- (void) catched
{
    NSLog(@"%s",__PRETTY_FUNCTION__);
}
- (void) escape
{
    NSLog(@"%s",__PRETTY_FUNCTION__);
}

@end


接口文件3:Dog.h

@interface Dog : NSObject <TProtocol>
- (void) catched;

@end




实现文件3:Dog.m

#import "Dog.h"

@implementation Dog
- (void) catched
{
    NSLog(@"%s",__PRETTY_FUNCTION__);
}

@end



接口文件4:TProtocol.h

#ifndef _008protocol_TProtocol_h
#define _008protocol_TProtocol_h
@protocol TProtocol <NSObject>
@required
- (void) catched;
@optional
- (void) escape;

@end
#endif



测试文件:main.m

#import <Foundation/Foundation.h>
#import "Hunter.h"
#import "Tiger.h"
#import "Dog.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool
    {
        Hunter *hunter = [[Hunter alloc] init];
        Tiger *tiger = [[Tiger alloc] init];
        Dog *dog = [[Dog alloc] init];
        
        hunter.animal = tiger;
        [hunter hunt];
        
        hunter.animal = dog;
        [hunter hunt];
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值