Objective-C中根据函数名调用函数

Objective-C中调用函数的方法是“消息传递”,这个和普通的函数调用的区别是,你可以随时对一个对象传递任何消息,而不需要在编译的时候声明这些方法。所以Objective-C可以在runtime的时候传递消息。

主要用到:SEL和@selector,当然还有performSelector

看例子:

先是三个函数:

-(void)CallBack0
{
    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];

这样就可以根据函数名调用函数啦!

posted on 2012-04-23 15:36  疯子123  阅读(112)  评论(0编辑  收藏  举报

导航