SEL sel = @selector (start:) ; // 指定action
if ([obj respondsToSelector:sel])
{ //判斷該對象是否有相應的方法
[obj performSelector:sel withObject:self]; //調用選擇器方法
}
使用[[UIApplication sharedApplication] keyWindow]查找應用程序的主窗口對象
respondsToSelector判斷是否實現了某方法
Tester.h
@interface Tester : NSObject {
}
-(void) test:(NSString*) msg;
-(void) notImp;
@end
@implementation Tester
-(void) test:(NSString*) msg
{
NSLog(@"%@", msg);
}
@end
main.m
#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;
}