0
点赞
收藏
分享

微信扫一扫

Objective-C 动态类型检测 类和实力对象能否响应方法


动态类型检测

 1.判断对象能否响应指定的方法
     -(BOOL) respondsToSelector : (SEL)
 2.判断类能否响应指定的方法
     -(BOOL) instanceRespondToSelector:(SEL)
   

实例代码:
   

<span style="font-size:14px;">#import <Foundation/Foundation.h>

//动物类
@interface Animal : NSObject
{
}
-(void)run;
@end

@implementation Animal
-(void)run{
NSLog(@"动物在跑!");
}
@end

//狗类
@interface Dog : NSObject
{
}
-(void)run;
-(void)eat;
@end

@implementation Dog
-(void)run{
NSLog(@"狗在跑!");
}
-(void)eat{
NSLog(@"狗在吃");
}
@end

//以下是动态类型检测
int main(int argc,const char * argv[]){
//以下是错误的,Animal类没有eat方法
Animal *animal = [Animal new];
[(Cat*)animal eat];


//以下讲isRespondsToSelector
//把eat方法包装成SEL类型
SEL s1 = @selector(eat);

//检测s1(也就是eat方法)能否响应 animal对象
BOOL isResponds = [animal respondsToSelector:s1];
//结果输出:0

//以下讲instanceRespondToSelector
//Dog类里有没有s1(指的是eat方法)
BOOL s2 = [Dog instanceRespondToSelector:s1];
//结果输出:1 因为Dog类里有eat方法

//还可以这么写
BOOL s3 = [Dog instanceRespondToSelector : @selector(eat)];//输出1
BOOL s4 = [animal instanceRespondToSelector : @selector(eat)];//输出0,Animal类里没有eat方法

return 0;
}</span>



举报

相关推荐

0 条评论