我有4个功能,我想每1秒随机执行一次无限时间。 这是我执行随机函数的代码:
-(void) Game
{
int rand = arc4random() % 5;
switch (rand) {
case 0:
[self appearred];
break;
case 1:
[self appearblue];
break;
case 2:
[self appearyellow];
break;
case 3:
[self appeargreen];
break;
}
}
但我怎么能每1秒重复一次这个功能?
答案 0 :(得分:0)
只需使用NSTimer。
PS:你不会100%确定这会每1秒附加一次。
答案 1 :(得分:0)
使用下面的代码,每1.0秒调用Game
方法。还有一件事,在您的Game
方法中,您需要使用% 4
代替% 5
来获取介于0到3之间的值。
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(Game)
userInfo:nil
repeats:YES];
-(void) Game
{
int rand = (int)arc4random() % 4;
switch (rand) {
case 0:
[self appearred];
break;
case 1:
[self appearblue];
break;
case 2:
[self appearyellow];
break;
case 3:
[self appeargreen];
break;
}
}
答案 2 :(得分:0)
您也可以尝试这样
*
-(void) Game
{
int rand = (int)arc4random() % 4;
switch (rand) {
case 0:
[self appearred];
break;
case 1:
[self appearblue];
break;
case 2:
[self appearyellow];
break;
case 3:
[self appeargreen];
break;
}
[self performSelector:@selector(Game) withObject:nil afterDelay:1.0];
}
*
每秒后会调用游戏功能