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

} 

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

4

3 回答 3

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];
于 2013-05-09T06:57:23.263 回答
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
}

希望能帮助到你

于 2013-05-09T06:59:58.877 回答
0

利用

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

得到你的统一随机索引。

然后使用它来访问函数指针数组,或者最好只使用索引来创建数据本身,正如@nhahtdh 在评论中建议的那样(这听起来更容易)。

于 2013-05-09T07:04:19.910 回答