respondsToSelector的相關使用(非常好用的方法,一定要了解!!!)
阿新 • • 發佈:2019-01-23
-(BOOL) isKindOfClass: classObj 用來判斷是否是某個類或其子類的例項
-(BOOL) isMemberOfClass: classObj 用來判斷是否是某個類的例項
-(BOOL) respondsToSelector: selector 用來判斷是否有以某個名字命名的方法(被封裝在一個selector的物件裡傳遞)
+(BOOL) instancesRespondToSelector: selector 用來判斷例項是否有以某個名字命名的方法. 和上面一個不同之處在於, 前面這個方法可以用在例項和類上,而此方法只能用在類上.
-(id) performSelector: selector
>
@interface Tester : NSObject {
}
-(void) test:(NSString*) msg;
-(void) notImp;
@end Tester.m #import "Tester.h"
@implementation Tester
-(void) test:(NSString*) msg
{
NSLog(@"%@", msg);
}
@end 注意:沒有實現notImp方法
#import "Tester.h"int main (int argc, constchar* 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];
return0;
}
SEL sel = @selector (start:) ; // 指定action
if ([obj respondsToSelector:sel])
{ //判斷該物件是否有相應的方法
[obj performSelector:sel withObject:self]; //呼叫選擇器方法
}
使用[[UIApplication sharedApplication] keyWindow]查詢應用程式的主視窗物件
respondsToSelector判斷是否實現了某方法
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 注意:沒有實現notImp方法
main.m
#import <Foundation/Foundation.h>#import "Tester.h"int main (int
{
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:
}
if([tester respondsToSelector:notImpSelector])
{
//test.m中沒有實現此主就去 [tester notImp];
}
[pool drain];
return0;
}