4特定间隔时间内的随机函数

时间:2014-03-09 11:46:14

标签: ios

我有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秒重复一次这个功能?

3 个答案:

答案 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];
    }

*

每秒后会调用游戏功能

相关问题