接口文件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;
}