我在课堂上有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 :(得分: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];
答案 1 :(得分: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
}
希望有所帮助
答案 2 :(得分:0)
使用
NSUInteger N = whatever;
NSUInteger randomIndex = arc4random_uniform((u_int32_t)N);
获得统一的随机索引。
然后使用它来访问函数指针数组,或者最好只使用索引来创建数据本身,就像@nhahtdh在评论中建议的那样(听起来更容易)。