Test.h
#import <Foundation/Foundation.h>
@interface Test : NSObject
-(void) test:(NSString*) msg;
-(void) notImp;//没有在Test.m中实现
@end
Test.m
#import "Test.h"
@implementation Test
-(void) test:(NSString*) msg
{
NSLog(@"%@", msg);
}
@end
main.m
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Test.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
//return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
id testObj = [[Test alloc] init];//注意,这里使用id
SEL testSelector = @selector(test:);
SEL notImpSelector = @selector(notImp:);
if([testObj respondsToSelector:testSelector])
{
[testObj test:@"tester.m中实现了test方法"];
}
if([testObj respondsToSelector:notImpSelector])
{
//test.m中没有实现notImp
[testObj notImp];
}
return 0;
}
}
notImp方法没有在.m文件中实现,所以[testObj respondsToSelector:notImpSelector]返回no;
respondsToSelector的作用:判断某个方法实现,那么就去调用,防止出现异常