ランダムな時間間隔でメソッドを繰り返し実行する最良の方法は何ですか。たとえば、メソッド内のコードは 1 秒、3 秒、7 秒、10 秒、11 秒、13 秒、19 秒、22 秒などで実行されます。無限の時間?
1412 次
4 に答える
6
私はタイマーを設定し、毎回乱数に対してチェックを行い、その乱数がヒットした場合は関数を呼び出します。
[NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES];
そしてtargetMethodで
if(arc4random() % 10 == 1)
{
//call your function
}
于 2012-06-27T15:00:43.950 に答える
2
int randomInt = (arc4random() % 100) + 1;
NSTimer *yourTimer = [NSTimer scheduledTimerWithTimeInterval:randomInt target:self selector:@selector(timedMethod:) userInfo:nil repeats:YES];
上記のコードは、1 秒から 100 秒以内のランダムな時間間隔で起動します
于 2012-06-27T14:59:41.687 に答える
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
于 2012-06-27T16:00:35.830 に答える
1
必要に応じて、または必要に応じて時間を定義し、計算して使用できます-
[NSTimer scheduledTimerWithTimeInterval:yourTime target:self selector:@selector(mainloop) userInfo:nil repeats:YES];
于 2012-06-27T15:00:32.420 に答える