Wal*_*ker 13 cocoa objective-c
我正在尝试创建一个倒计时器,它将倒计时,一个连接到文本字段的IBOutlet,从60秒降低到0.我不确定
A.如何将重复限制为60和
B.如何提前减少倒计时:
- (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];
}
Run Code Online (Sandbox Code Playgroud)
e.J*_*mes 19
到目前为止,你走在正确的轨道上.
坚持使用您已有的代码,这里是advanceTimer方法应该如何使其工作:
- (void)advanceTimer:(NSTimer *)timer
{
[countdown setIntegerValue:([countdown integerValue] - 1)];
if ([countdown integerValue] == 0)
{
// code to stop the timer
}
}
Run Code Online (Sandbox Code Playgroud)
编辑: 为了使整个事物更加面向对象,并避免每次从字符串转换为数字并返回,我会做这样的事情:
// Controller.h:
@interface Controller
{
int counter;
IBOutlet NSTextField * countdownField;
}
@property (assign) int counter;
- (IBAction)startCountdown:(id)sender;
@end
Run Code Online (Sandbox Code Playgroud)
// 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
Run Code Online (Sandbox Code Playgroud)
And, if you can make use of bindings, you could simply bind the text field's intValue到的counter属性Controller.这将允许您IBOutlet在类接口和setIntegerValue:线路中消除advanceTimer.
更新:删除了将计时器添加到运行循环两次的代码.感谢Nikolai Ruhe和nschmidt注意到这个错误.
更新:setIntegerValue根据nschmidt,使用该方法简化代码.
编辑:错误定义(void)advanceTimer:(NSTimer*)计时器...导致恼人的'无法识别的选择器发送到实例'异常
您可以添加实例变量int _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];
}
Run Code Online (Sandbox Code Playgroud)