2012-06-27 40 views

回答

5

我會設置一個計時器,並在每次通過檢查一個隨機數,如果該隨機數命中,然後調用該函數:

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

,並在targetMethod

if(arc4random() % 10 == 1) 
{ 
    //call your function 
} 
2
int randomInt = (arc4random() % 100) + 1; 
NSTimer *yourTimer = [NSTimer scheduledTimerWithTimeInterval:randomInt target:self selector:@selector(timedMethod:) userInfo:nil repeats:YES]; 

上面的代碼將在1s內火在隨機時間間隔100秒

1

您可以定義時間按需要或你想要的,計算它和使用 -

[NSTimer scheduledTimerWithTimeInterval:yourTime target:self selector:@selector(mainloop) userInfo:nil repeats:YES]; 
1

試試這個:

-(void) executeMethod 
{ 
    NSLog(@"Method being executed"); 
} 

-(void) callingRandomTimedMethod 
{ 
    for (int i = 1; i > 0; i=i+2) { 
     [self executeMethod]; 
     sleep(i); 
    } 
} 

這給像輸出(檢查時間間隔):

> 2012-06-27 11:59:31.757 FirstApp[804:fb03] Method being executed 
> 2012-06-27 11:59:32.760 FirstApp[804:fb03] Method being executed 
> 2012-06-27 11:59:35.762 FirstApp[804:fb03] Method being executed 
> 2012-06-27 11:59:40.765 FirstApp[804:fb03] Method being executed 
> 2012-06-27 11:59:47.767 FirstApp[804:fb03] Method being executed 
> 2012-06-27 11:59:56.769 FirstApp[804:fb03] Method being executed 
+0

當然不是最好的辦法。 –

+0

代碼會在睡眠時完全掛起..不太好用這個。 – Floris497