Iphone 以随机时间间隔执行方法
以随机时间间隔重复执行方法的最佳方式是什么,例如,方法中的代码以1s、3s、7s、10s、11s、13s、19s、22s等速度运行,。无限长的时间Iphone 以随机时间间隔执行方法,iphone,objective-c,ios,cocoa-touch,sdk,Iphone,Objective C,Ios,Cocoa Touch,Sdk,以随机时间间隔重复执行方法的最佳方式是什么,例如,方法中的代码以1s、3s、7s、10s、11s、13s、19s、22s等速度运行,。无限长的时间 int randomInt = (arc4random() % 100) + 1; NSTimer *yourTimer = [NSTimer scheduledTimerWithTimeInterval:randomInt target:self selector:@selector(timedMethod:) userInfo:nil repea
int randomInt = (arc4random() % 100) + 1;
NSTimer *yourTimer = [NSTimer scheduledTimerWithTimeInterval:randomInt target:self selector:@selector(timedMethod:) userInfo:nil repeats:YES];
上述代码将在1s到100s的随机时间间隔内触发您可以根据需要或根据需要定义时间,计算并使用-
[NSTimer scheduledTimerWithTimeInterval:yourTime target:self selector:@selector(mainloop) userInfo:nil repeats:YES];
我会设置一个计时器,每次通过检查一个随机数,如果该随机数命中,则调用函数:
[NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES];
在targetMethod中
if(arc4random() % 10 == 1)
{
//call your function
}
试试这个:
-(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