Search code examples
objective-ccocoanstimer

Generating a random time interval in Cocoa


I am pretty new to Cocoa, but I am trying to put a simple reaction game together. Therefore I need to generate the time intervall of the NSTimer randomly. Currently I have tried the code below.

int randomNumber = rand() %5;

changeColor = [NSTimer scheduledTimerWithTimeInterval:(randomNumber) target:self selector:@selector(changeBackground) userInfo:nil repeats:YES];

Solution

  • If you want resolution finer than 1 second, you should create a double from the random number. Perhaps like this:

    int sourceRandom100x = rand() % 500; // i.e. 435
    double randomInterval = sourceRandom100x/100.0  // 4.35
    
    [NSTimer scheduledTimerWithTimeInterval:(randomInterval) ...
    

    But the technique will use the same interval for every iteration. If you want a freshly-random interval every time, make the timer not repeat, and inside changeBackground, setup another one (via delegation to a more appropriately named new method, such as -(void) setupRandomBackgroundChangeTimerIfNecessary