#import <Foundation/Foundation.h>
@interface Tester : NSObject {
}
-(void) test:(NSString*) msg;
-(void) notImp;
@end
#import "Tester.h"
@implementation Tester
-(void) test:(NSString*) msg
{
NSLog(@"%@", msg);
}
@end
#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 动态方法调用
本文介绍了一个Objective-C程序实例,展示了如何通过id类型变量进行动态方法调用,并检查方法是否被实现。该程序首先定义了一个名为Tester的类,包含两个方法:test和notImp。然后,在main函数中通过id类型的变量调用这些方法,并使用 respondsToSelector 方法来判断对象是否响应特定的选择器。
787

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



