有没有人想教我如何使用NSTimer
使用循环过程?我有2个进程计时器,timer1和timer2重复到n循环(timer1 - > timer2 - > timer1 - > timer2,依此类推,直到n循环)由一个按钮触发。我是xcode的新手。请教我。两个计时器都由用户输入。如果可能,请举个例子。
我的代码应该是这样的。如果我错了,请告诉我
- (void) timer2Elapsed:(NSTimer *) timer;
{
...
displayCountDown.text = [NSString stringWithFormat:@"%d : %d : %d", hour , minute, second];
}
- (void)timer1Elapsed: (NSTimer *) timer;
{
...
displayCountDown.text = [NSString stringWithFormat:@"%d : %d : %d", hour , minute, second];
}
我的按钮触发倒计时:
- (IBAction)startBtn:(id)sender {
endSetTime = [NSDate timeIntervalSinceReferenceDate] + totalSecondTime;
endSetRest = [NSDate timeIntervalSinceReferenceDate] + totalSecondRest;
countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 0.99 target: self selector: @selector(timer1Elapsed:) userInfo: nil repeats: YES];
}
有人告诉我使用这段代码,但我不知道我应该在里面写什么以及把它放在哪里?他说循环?我不知道?以及如何在我的按钮内连接该代码?
+ (void) startTimer:(id)timer
{
static int numberOfTimes = 0;
if(numberOfTimes >= 5)
{
numberOfTimes = 0;
return;
}
numberOfTimes ++;
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timer1Elapsed:) userInfo:nil repeats:NO];
}
答案 0 :(得分:0)
忘记计时器。使用performSelector:withObject:afterDelay:selector。
@interface CECountdown : NSObject {
NSDate *_startDate;
NSTimeInterval _countdownInterval;
}
@end
@implementation CECountdown
- (id)initWithCountdownInterval:(NSTimeInterval)interval {
self = [super init];
if(self) {
_countdownInterval = interval;
_startDate = [[NSDate date] retain];
}
return self;
}
- (void)dealloc {
[_startDate release];
[super dealloc];
}
- (void)method0 {
// Do something
[self performSelector:@selector(method1) withObject:nil afterDelay:0.3];
[self checkTimeout];
}
- (void)method1 {
// Do something
[self performSelector:@selector(method0) withObject:nil afterDelay:0.3];
[self checkTimeout];
}
- (void)invalidate {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(method1) object:nil];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(method2) object:nil];
}
- (void)checkTimeout {
if([NSDate timeIntervalSinceReferenceDate] - [_startDate timeIntervalSinceReferenceDate] > _countdownInterval) {
[self invalidate];
}
}
- (void)didTapStartButton:(id)sender {
[self performSelector:@selector(method1) withObject:nil afterDelay:0.3];
}
@end