#import <Foundation/Foundation.h>
#import "Dog.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 动态类型检测的第二部分
// 1. 方法响应的检测
Animal *ani = [Animal new];
// 判断,如果ani 能够调用 eat方法,然后就调用
//[(Dog *)ani eat];
// 1)判断实例对象能否响应(调用)指定方法
SEL s1 = @selector(eat); // 把eat包装成SEL类型
BOOL isRespond = [ani respondsToSelector:s1];
NSLog(@"isRespond = %d", isRespond);
if (isRespond) {
[(Dog *)ani eat];
} else{
NSLog(@"该对象不能调用此方法");
}
// 2)判断类中有没有(调用)指定的方法
// 1
isRespond = [Dog instancesRespondToSelector:s1];
NSLog(@"isRespond = %d", isRespond);
// 1 Dog类中虽然没有run方法,但是Dog类继承自Animal类,Animal类中有run方法
isRespond = [Dog instancesRespondToSelector:@selector(run)];
NSLog(@"isRespond = %d", isRespond);
}
return 0;
}
判断对象能否响应指定的方法
最新推荐文章于 2024-09-29 17:14:14 发布