如何根据整数变量的输出调用IBAction?

时间:2013-12-24 07:51:32

标签: ios objective-c

假设我有5种IBAction方法

-(IBAction)tappedBlock1:(id)sender
{
           self.block1.image = self.oImg;
}
-(IBAction)tappedBlock2:(id)sender
{
       self.block2.image = self.oImg;
}
-(IBAction)tappedBlock3:(id)sender
{
           self.block3.image = self.oImg;
}
-(IBAction)tappedBlock4:(id)sender
{
       self.block4.image = self.oImg;
}
-(IBAction)tappedBlock5:(id)sender
{
        self.block5.image = self.oImg;
}

另一个从1 - 5生成随机数的函数 现在根据我要调用动作的随机数。
我正在使用if-else语句来执行此操作,但它会大大增加我的代码的大小 下面是代码

-(void)generateRandom
{
    NSInteger random;
reCheckrandom:random = arc4random()%5;
    if(random == 0)
    {
        [self tappedBlock1:self];
    }
    if(random == 1)
    {
        [self tappedBlock2:self];
    }
    if(random == 2)
    {
        [self tappedBlock3:self];
    }
    if(random == 3)
    {
        [self tappedBlock4:self];
    }
    if(random == 4)
    {
        [self tappedBlock5:self];
    }


}

有没有更好的方法来执行相同的操作?

3 个答案:

答案 0 :(得分:2)

您可以使用NSSelectorFromString生成字符串的选择器,例如:

-(void)generateRandom
{
    NSInteger random;
    random = arc4random()%5;

    NSString *method = [NSString stringWithFormat:@"tappedBlock%d",random];
    SEL s = NSSelectorFromString(method);
    [self performSelector:s withObject:self];
}

答案 1 :(得分:1)

您可以动态生成选择器的名称:

    SEL selector = NSSelectorFromString([NSString stringWithFormat:@"tappedBlock%ld",(long)random]);

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self performSelector:selector withObject:self];
#pragma clang diagnostic pop

#pragmas沉默了关于内存泄漏的恼人警告。

答案 2 :(得分:0)

通过查看你的代码,我认为你只需要一个函数:

-(void)generateRandom
{
    [self.blocks[arc4random()%self.blocks.count] setImage:self.oImg];
}

其中self.blocks是您NSArray的阻止。