Objective c 倒数计时器
我正在尝试创建一个倒计时计时器,它将倒计时(一个连接到文本字段的IBOutlet)从60秒降到0秒。我不确定 A.如何将重复次数限制为60次,以及 B.如何提前减少倒计时计时器:Objective c 倒数计时器,objective-c,cocoa,Objective C,Cocoa,我正在尝试创建一个倒计时计时器,它将倒计时(一个连接到文本字段的IBOutlet)从60秒降到0秒。我不确定 A.如何将重复次数限制为60次,以及 B.如何提前减少倒计时计时器: - (IBAction)startCountdown:(id)sender { NSTimer *countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(advanceTimer:
- (IBAction)startCountdown:(id)sender
{
NSTimer *countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(advanceTimer:) userInfo:nil repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:countdownTimer forMode:NSDefaultRunLoopMode];
}
- (void)advanceTimer:(NSTimer *)timer
{
[countdown setIntegerValue:59];
}
到目前为止,你在正确的轨道上 坚持使用您已有的代码,下面是
advanceTimer
方法如何使其工作:
- (void)advanceTimer:(NSTimer *)timer
{
[countdown setIntegerValue:([countdown integerValue] - 1)];
if ([countdown integerValue] == 0)
{
// code to stop the timer
}
}
编辑:
为了使整个过程更加面向对象,并避免每次都从字符串转换为数字,我将执行以下操作:
// Controller.h:
@interface Controller
{
int counter;
IBOutlet NSTextField * countdownField;
}
@property (assign) int counter;
- (IBAction)startCountdown:(id)sender;
@end
// Controller.m:
@implementation Controller
- (IBAction)startCountdown:(id)sender
{
counter = 60;
NSTimer *countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(advanceTimer:)
userInfo:nil
repeats:YES];
}
- (void)advanceTimer:(NSTimer *)timer
{
[self setCounter:(counter -1)];
[countdownField setIntegerValue:counter];
if (counter <= 0) { [timer invalidate]; }
}
@end
//Controller.m:
@执行控制器
-(iAction)开始计数:(id)发送方
{
计数器=60;
NSTimer*倒计时=[NSTimer scheduledTimerWithTimeInterval:1
目标:自我
选择器:@选择器(高级计时器:)
用户信息:无
重复:是];
}
-(无效)高级计时器:(NSTimer*)计时器
{
[自动设置计数器:(计数器-1)];
[countdownField setIntegerValue:计数器];
if(counter您可以添加一个实例变量int\u timerValue来保存计时器值,然后执行以下操作。还请注意,您正在创建的NSTimer已在当前运行循环中计划
- (IBAction)startCountdown:(id)sender
{
_timerValue = 60;
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(advanceTimer:) userInfo:nil repeats:NO];
}
- (void)advanceTimer:(NSTimer *)timer
{
--_timerValue;
if(self.timerValue != 0)
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(advanceTimer:) userInfo:nil repeats:NO];
[countdown setIntegerValue:_timerValue];
}
倒计时被添加到运行循环中两次,这是错误的。@Nikolai Ruhe:谢谢你指出这一点。我已经从示例中删除了错误的代码。我想setIntegerValue比[NSString stringWithFormat:]更有效,所以我不会进行这种“优化”。尤其是因为它无助于代码的清晰性。@nschmidt:我肯定你是对的。我不确定它的用法,而且我面前没有编译器,所以我只使用我知道可以使用的工具。@nschmidt:我已将它改回setIntegerValue。关于增加的混乱,你完全正确。