标签:
选择器:是一种变量的类型,用于存储方法,类似于C语言的函数指针
作用:用于UI控件的点击事件
新建一个Dog的类
在Dog.m中写两个方法
<span style="font-size:14px;">#import "Dog.h"
@implementation Dog
- (void)bark{
NSLog(@"狗在叫");
}
- (void)barkToPeople:(NSString *)name{
NSLog(@"狗向%@叫",name);
}
@end
</span><span style="font-size:14px;">#import <Foundation/Foundation.h>
#import "Dog.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Dog * daodao = [[Dog alloc] init];
//狗叫的方法
[daodao bark];
//狗像某人叫得方法
[daodao barkToPeople:@"Snail"];
//定义一个选择器
SEL sel = @selector(bark);
//判断daodao是否有bark的方法
if ([daodao respondsToSelector:sel]) {
[daodao performSelector:sel];
}
//有参数的选择器
SEL sel2 = @selector(barkToPeople:);
if ([daodao respondsToSelector:sel2]) {
//给狗像某人叫得方法 加一个参数
[daodao performSelector:sel2 withObject:@"Snail"];
}
//选择器最多只能加两个参数 所以有一定的局限性
/*
营造一种运行情况
在控制台输入一个函数的名字
然后转换为OC的字符串对象
然后判断daodao是否有这个方法 然后再执行一系列操作
*/
char c[20] = {};
scanf("%s",c);
NSString * inputStr = [[NSString alloc] initWithUTF8String:c];
//根据一个字符串生成一个选择器
SEL sel3 = NSSelectorFromString(inputStr);
if ([daodao respondsToSelector:sel3]) {
[daodao performSelector:sel3];
}else{
NSLog(@"刀刀没有%@方法",inputStr);
}
}
return 0;
}
</span>版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/qq1791422018/article/details/47039945