Sakir saiyed
Sakir saiyed

Reputation: 742

How to schedule or call a method at random time interval in cocos2d iphone

I want to call a method at Irregular time interval means it should be random time plus i want it in some define range too.

Like : it should call at any second between 3 to 8 .

I tried this one :

[NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(myMethod:)  userInfo:nil repeats: YES];

void mymethod()
{
  if(arc4random() % 10 == 1)
  {
      // calling my method here;
  }
}

This way , i am not getting randomization which i want.

Any one can please help me on this !!!

Upvotes: 0

Views: 509

Answers (1)

Renaissance
Renaissance

Reputation: 554

Here you can make a scheduler which will get called at random interval.

-(void)randomTimeScheduler{


int time = arc4random()%5;
int nextTimeOfCall = 3+time;

NSLog("it will be called after:%d",nextTimeOfCall);

[self performSelector:@selector(randomTimeScheduler) withObject:self afterDelay:nextTimeOfCall];

}

You have to call it from your class and then it will work as a scheduler. And it has finite interval time 3-8.

Upvotes: 1

Related Questions