本帖最后由 wangchao1992 于 2015-8-17 17:50 编辑
动态类型检测: 响应方法
Animal *ani = [Dog new];
SEL s1 = @selector(eat);
1)通过performSelector响应无参的方法
if ([ani respondsToSelector:s1]) {
//[(Dog*)ani eat];
[(Dog*)ani eat:@"一块沾有粑粑的巧克力"]; //有参
[ani performSelector:s1]; //作用,响应方法 没有参数
}else{
NSLog(@"该对象不能调用此方法");
}
2)通过performSelector: withObject:响应有参的方法
SEL s2 = @selector(eat:);
[ani performSelector:s2 withObject:@"一块沾有粑粑棒棒糖"];
3)通过performSelector: withObject: withObject:响应有两个参的方法
[ani performSelector:@selector(eat:andFoodName:) withObject:@"班长养得饿狗" withObject:@"一块沾有粑粑的棒棒糖"];
Animal类
#import <Foundation/Foundation.h>
@interface Animal : NSObject
-(void)run;
@end
Dog 类
#import "Animal.h"
@interface Dog : Animal
-(void)eat;
-(void)eat:(NSString *)foodName;
-(void)eat:(NSString *)dogName andFoodName:(NSString *) foodName;
@end
|
|