现在这里是我正在使用的代码。它仅在按下按钮时更新,并且是平均值而不是瞬时值。
-(IBAction)button:(id)sender {
[self incrementTapCount];
NSMutableString *aString = [NSMutableString stringWithFormat:@"%.2f", averageTapsPerSecond];
[aString appendFormat:@"%s", " per second"];
current.text = aString;
}
- (void)incrementTapCount
{
tapCountInPastSecond++;
}
- (void)timerActions
{
secondsElapsed = secondsElapsed + .1;
averageTapsPerSecond = (averageTapsPerSecond*(secondsElapsed-.1) +tapCountInPastSecond) / secondsElapsed ;
tapCountInPastSecond = 0;
}
在视图上加载...
[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(timerActions) userInfo:Nil repeats:YES];
我试图在不按下按钮的情况下进行更新,而不是平均速度,而是当时的速度。
答案 0 :(得分:0)
你的计时器每隔0.1秒触发一次,你想在最后一秒保持一个“滑动”的总和。我建议一个10个整数的数组。每次计时器滴答时,您可以将最新的点击计数添加到数组的末尾并减去最旧的。
@property (assign) NSInteger runningTotal;
@property (assign) NSInteger tapsInLastSample;
@property (strong,nonatomic) NSMutableArray *tapHistory;
-(void) viewDidLoad {
[super viewDidLoad];
self.runningTotal=0;
self.tapHistory=[NSMutableArray arrayWithCapacity:11];
[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(timerActions) userInfo:Nil repeats:YES];
}
-(IBAction)button:(id)sender {
self.tapsInLastSample++;
}
- (void)timerActions {
self.runningTotal+=self.tapsInLastSample;
[self.tapHistory addObject:[NSNumber numberWithInteger:self.tapsInLastSample]];
if (self.tapHistory.count >10) {
self.runningTotal-=[self.tapHistory[0] integerValue];
[self.tapHistory removeObjectAtIndex:0];
}
current.text=[NSString stringWithFormat:@"Taps in last second=%ld",(long)self.runningTotal];
self.tapsInLastSample=0;
}