我有一个必须每1秒调用一次的函数。我试图让它在函数结束时调用自身,或让它调用一个单独的函数,然后在一秒钟之后调用原始函数。两次尝试都失败了 - NSLog显示调用的函数比每1秒钟快得多。
第一种方法:
- (void) startPlacingUser
{
NSString *bigMLLocation = [self predictLocationWith:locationRSSiValues];
[self performSelector: @selector(startPlacingUser) withObject:nil afterDelay: 1];
}
这个只是每隔0.3秒左右调用一次,时间不一致 - 有时更快,有时更慢。函数predictLocation是一个只返回字符串的大if语句。
第二种方法:
- (void) startPlacingUser
{
NSString *bigMLLocation = [self predictLocationWith:locationRSSiValues];
[self placeUserAgain];
}
-(void) placeUserAgain
{
[NSThread sleepForTimeInterval:1];
[self startPlacingUser];
}
此方法每秒调用startPlacingUser 100次。
这两个都给了调用startPlacingUser的疯狂时机,而且它绝对不是每1秒钟。
答案 0 :(得分:1)
您可以使用NSTimer在给定时间后调用精确功能
...
NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
selector: @selector(startPlacingUser:) userInfo: nil repeats: YES];
...
...
-(void) startPlacingUser:(NSTimer*) t
{
NSString *bigMLLocation = [self predictLocationWith:locationRSSiValues];
}
您当前的解决方案无法正常工作,并可能导致堆栈溢出。
答案 1 :(得分:-1)
将sleepForTimeInterval更改为1000,而不是秒,而是毫秒