4

我制作了一个带有计时器的 RunLoop,它可以更新显示倒计时的标签。一旦倒计时达到零,我需要 RunLoop 停止,对于计时器正常结束的情况,我可以使用 runUntilDate,日期是当前日期 + 倒计时时间。问题是当用户在完成之前取消按钮的倒计时。我不知道如何告诉 RunLoop 停止取消按钮操作。这是 RunLoop 的代码:

    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                            [self methodSignatureForSelector:@selector(updateCountdownLabel:)]];
[invocation setTarget:self];
[invocation setSelector:@selector(updateCountdownLabel:)];
[[NSRunLoop mainRunLoop] addTimer:[NSTimer timerWithTimeInterval:1 invocation:invocation repeats:YES] forMode:NSRunLoopCommonModes];

该方法只是告诉标签在每个循环中减少 1。

我可以告诉取消按钮将标签更改为零,并让运行循环选择器检查值是否为零,但运行循环自己的选择器可以告诉它停止吗?

cancelPerformSelector:target:argument:

cancelPerformSelectorsWithTarget:

这些是我发现的最接近的,但它们似乎不能从 RunLoops 自己的选择器内部工作,或者至少我没有以任何方式尝试过它们。

基本上我需要让按钮告诉 RunLoop 停止,或者以某种方式从它自己的选择器中停止 RunLoop。

谢谢。

4

1 回答 1

13

你还没有创建一个运行循环,你已经安排了一个计时器在主运行循环上开始。

您应该做的是NSTimer在运行循环上调度计时器之前将您创建的对象存储为实例变量。

在您的updateCountdownLabel:方法中,一旦您的结束条件得到满足,只需调用-invalidate您的计时器实例。这将从运行循环中删除计时器,并且由于您从未保留它,它将被释放。

我已经更新了使用基于选择器NSTimer而不是NSInvocation基于您的方法的方法。这意味着回调方法签名按照您的预期定义。它还避免了将NSTimer对象存储在 ivar 中的需要:

- (void)startCountDown
{

    NSTimer* timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateCountdownLabel:) userInfo:nil repeats:YES]
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}


- (void)updateCountdownLabel:(NSTImer*)timer
{
    if(thingsAreAllDone)
    {
        [timer invalidate];
    }
}
于 2011-07-08T06:56:13.040 回答