标签:
// MyProtocol.h
#import <Foundation/Foundation.h>
@protocol MyProtocol <NSObject>
@optional
- (void)print:(int)value;
@required
- (int)printValue:(int)value1 andValue:(int)value2;
@end
// MyTest.h
#import <Foundation/Foundation.h>
#import "MyProtocol.h"
@interface MyTest : NSObject <MyProtocol>
- (void)showInfo;
@end
// MyTest.m
#import "MyTest.h"
@implementation MyTest
- (void)showInfo{
NSLog(@"showInfo...");
}
- (int)printValue:(int)value1 andValue:(int)value2{
NSLog(@"value1 = %d, value2 = %d", value1, value2);
return 0;
}
// 下面这个方法可以实现,也可以不实现
- (void)pirnt:(int)value{
NSLog(@"value = %d", value);
}
@end
// mian.m
#import <Foundation/Foundation.h>
#import "MyTest.h"
#import "MyProtocol.h"
int main(int argc, const char *argv[]){
// 普通类的调用方法
MyTest *myTest = [[MyTest alloc] init];
[myTest showInfo];
SEL sel = @selector(print:);
// 确定这个print方法是否实现
if([myTest respondsToSelector:sel]){
[myTest print:20];
}
[myTest printValue:20 andValue:10];
// 使用协议的方式来调用
id<MyProtocol> myProtocol = [[MyTest alloc] init];
if([myProtocol respondsToSelector:@selector(print:)]){
[myProtocol print:10];
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/lianfu/p/4779158.html