Objective-C中根据函数名调用函数
http://blog.csdn.net/wangqiuyun/article/details/7489872
Objective-C中调用函数的方法是“消息传递”,这个和普通的函数调用的区别是,你可以随时对一个对象传递任何消息,而不需要在编译的时候声明这些方法。所以Objective-C可以在runtime的时候传递消息。
主要用到:SEL和@selector,当然还有performSelector
看例子:
先是三个函数:
{
NSLog(@"CallBack0");
}
-(void)CallBack1:(int)a
{
NSLog(@"CallBack1:a=%i",a);
}
-(void)CallBack2:(int)a b:(int)b
{
NSLog(@"CallBack2:a=%i,b=%i",a,b);
}
performSelector调用:
[self performSelector:@selector(CallBack0)];
[self performSelector:@selector(CallBack1:) withObject:1];
[self performSelector:@selector(CallBack2:b:) withObject:1 withObject:2];
根据函数名动态调用:
NSString *a=@"CallBack0";
SEL faSelector=NSSelectorFromString(a);
[self performSelector:faSelector];
NSString *b=@"CallBack1:";
SEL fbSelector=NSSelectorFromString(b);
[self performSelector:fbSelector withObject:1];
NSString *c=@"CallBack2:b:";
SEL fcSelector=NSSelectorFromString(c);
[self performSelector:fcSelector withObject:1 withObject:2];
这样就可以根据函数名调用函数啦!