Tester.h
#import < Foundation / Foundation.h >
@interface Tester : NSObject {
}
- ( void ) test:(NSString * ) msg;
- ( void ) notImp;
@end
Tester.m
#import " Tester.h "
@implementation Tester
- ( void ) test:(NSString * ) msg
{
NSLog( @" %@ " , msg);
}
@end
main.m
#import < Foundation / Foundation.h >
#import " Tester.h "
int main ( int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id tester = [[Tester alloc] init]; // 注意,这里使用id
SEL testSelector = @selector(test:);
SEL notImpSelector = @selector(notImp:);
if ([tester respondsToSelector:testSelector])
{
// tester.m中实现了test方法
[tester test: @" invoke test method " ];
}
if ([tester respondsToSelector:notImpSelector])
{
// test.m中没有实现此主就去
[tester notImp];
}
[pool drain];
return 0 ;
}
本文通过一个简单的Objective-C示例程序介绍了如何使用id类型变量调用不同方法,并演示了如何检查对象是否响应特定的选择器。文章重点在于理解Objective-C运行时的消息发送机制,包括如何判断对象是否能响应某个方法。

587

被折叠的 条评论
为什么被折叠?



