2013-05-09 47 views
1

我在一个类中有7个方法。当我收到特定的消息时,我必须从这7种方法中随机调用一种方法。 我的示例代码:随机调用方法

-(void)poemAbcd{ 

    UIImage *image = [UIImage imageNamed: @"abcd_bg.png"]; 
    [backgroundImage setImage:image]; 

    [self changeMumuPosition:80 with:220]; 
} 

-(void)poemHumptyDumpty{ 

    UIImage *image = [UIImage imageNamed: @"humpty_dumpty.png"]; 
    [backgroundImage setImage:image]; 

    [self changeMumuPosition:80 with:170]; 
} 

-(void)poemBlackship{ 

    UIImage *image = [UIImage imageNamed: @"black_sheep.png"]; 
    [backgroundImage setImage:image]; 

    [self changeMumuPosition:66 with:229]; 
} 

-(void)poemRowRow{ 

    UIImage *image = [UIImage imageNamed: @"boat_bg.png"]; 
    [backgroundImage setImage:image]; 

    [self changeMumuPosition:144 with:211]; 
} 

-(void)poemHappy{ 

    UIImage *image = [UIImage imageNamed: @"boat_bg.png"]; 
    [backgroundImage setImage:image]; 

    [self changeMumuPosition:144 with:211]; 
} 

-(void)poemItsyBitsy{ 

    UIImage *image = [UIImage imageNamed: @"boat_bg.png"]; 
    [backgroundImage setImage:image]; 

    [self changeMumuPosition:144 with:211]; 
} 

-(void)poemTwinkleTwinkle{ 

    UIImage *image = [UIImage imageNamed: @"twincle_twincle_little_star.png"]; 
    [backgroundImage setImage:image]; 

    [self changeMumuPosition:70 with:222]; 
} 

分为以下几个方法我想从这些方法7随机调用一个方法。

-(void)poemRandom{ 

     //Call a method randomly from those 7 methods 

} 

我该怎么做?先谢谢您的帮助。

+0

这是什么意思“随机”在这里? – Bhavin 2013-05-09 06:54:47

+6

而不是随机调用一个方法,因为他们都做同样的工作(在数据只是一些差别),可以封装数据,并随机挑选其中一组数据,以显示代替。 – nhahtdh 2013-05-09 06:58:17

回答

1

一个草率的方式行做到这一点:

-(void)poemRandom{ 
    int nr = arc4random() % 7; 
    if (nr == 0) [self poemAbcd]; 
    else if (nr == 1) [self poemHumptyDumpty]; 
    else if (nr == 2) [self poemBlackship]; 
    //and so on 
} 

希望它可以帮助

+0

非常感谢你兄弟。 – Leo 2013-05-09 07:10:55

6

一种方法是将函数指针添加到数组中,然后从中选择一个。 SEL是包装在Objective-C选择的方式,所以你可以使用的东西沿着

// edited, fixed data structure, props to xlc 
// don't forget to set array size according to function count 
SEL funcionsArray[7] = { @selector(poemAbcd), @selector(poemHumptyDumpty), /* etc */ }; 
// randomIndex is a randomly selected number from 0 to [number-of-selectors] - 1 
SEL randomSel = funcionsArray[randomIndex]; 
[self performSelector:randomSel]; 
+3

你不能这样做,因为SEL不是objc对象。然而可以有'SEL阵列[7]' – 2013-05-09 07:01:56

+0

...和你必须添加INT randomIndex = arc4random()%[functionsArray计数]; – 2013-05-09 07:02:06

+0

@xlc,感谢您的更正。随机数是一个微不足道的,所以我决定从示例代码中排除它。 – Alexander 2013-05-09 07:04:26

0

使用

NSUInteger N = whatever; 
NSUInteger randomIndex = arc4random_uniform((u_int32_t)N); 

得到你的统一随机指数。

然后使用该访问函数指针阵列,或优选地只使用索引来创建数据本身,@nhahtdh评价建议(听起来比较容易的方式)。