【问题标题】:NStimer and for loopNStimer 和 for 循环
【发布时间】:2011-02-20 08:28:18
【问题描述】:

我正在为此苦苦挣扎。我看到了一些可以执行此操作的代码:

- (void)startTimer {
    pauseTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doActions) userInfo:nil repeats:YES];
} 

然后在 doActions 中调用它。

问题是我想在按下按钮时调用它,并且执行操作是 IBaction。我不断收到sigAbrt

有人可以给我一些示例代码,您可以在按下按钮时每 1 秒将标签从“on”更改为“off”吗?

编辑

我的意思是如果 doActions 看起来像这样

- (IBAction) doActions {
for(int j; j<100; j++){

theLabel.hidden != theLabel.hidden;
//Does invalidate timer go here?
}
}

【问题讨论】:

  • 您可以发布您的doActions 方法吗?我认为这将帮助我们引导您朝着正确的方向前进——无论是出于设计目的还是功能目的。
  • "然后在 doActions 中调用它。"等等:你是说在-(IBAction)doActions 中有一行[self startTimer];?这意味着每隔约 1 秒,您将为您已经创建的每个计时器创建一个额外的计时器。 (这意味着大约 20 秒后,您将超过惊人的 100 万 个计时器...)
  • 仍然不确定您在谈论以下两个动作序列中的哪一个?序列1:用户触摸屏幕上的按钮,用户再次抬起手指,然后应该每秒切换一次但不超过100次。序列 2:用户触摸屏幕,手指仍然向下时每秒切换一次,直到手指再次抬起,但不超过 100 次。无论哪种方式: for 循环都无法工作。当您启动计时器时,设置一个您递增的 ivar,并在您的 separate timerFired 方法中检查。如果大于 100,则计时器无效

标签: iphone loops for-loop nstimer


【解决方案1】:

我仍然不清楚您要完成什么:毕竟,如果您只是用简单的英语写下来,我会发现它要容易得多

也就是说,我认为会带你去你想去的地方:

// Assuming ivars:
// NSTimer* toggleTimer
// NSUInteger toggleCount

- (void)toggleTimerFired:(NSTimer*)timer
{
  if ( toggleCount++ >= 100 ) {
    [self stopToggling:self];
    return;
  }
  // do whatever you need to do a hundred times here
}

- (IBAction)stopToggling:(id)sender
{
  [toggleTimer invalidate], toggleTimer = nil;  // you don't want dangling pointers...
  // perform any other needed house-keeping here
}

- (IBAction)startToggling:(id)sender
{
  [self stopToggling:self]; // if `startToggling:` will NEVER be called when a timer exists, this line CAN be omitted.
  toggleCount = 0;
  toggleTimer = [NSTimer scheduledTimerWithTimeInterval:1. target:self selector:@selector(toggleTimerFired:) userInfo:nil repeats:YES];
}

根据确切您想要做什么,startToggling: 需要发送到touchUpInsidetouchDown。在第二种情况下,stopToggling: 可能需要在按钮的任何touchUp... 事件上调用。

【讨论】:

    【解决方案2】:
    - (void)startTimer {
        pauseTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doActions) userInfo:nil repeats:YES];
    } 
    
    - (void) doActions {
    theLabel.hidden != theLabel.hidden;
    }
    

    【讨论】:

    • 谢谢,但是!如果 doactions 是 (IBaction)doActions。还是我应该制作一个单独的功能蚂蚁然后在我的按钮操作中调用它?
    • 如果我需要它在一个循环中循环说 100 次怎么办?
    • 只要 doActions 没有参数 @selector(doActions) 就可以。当它确实需要参数时,请参阅stackoverflow.com/questions/1349740/…> 我不明白您的循环是什么意思。如果您的意思是计时器需要调用 100 次?然后增加一个计数器(实例变量)来实现这一点。添加 if 语句以在达到一定数量时使 pauseTimer 失效。
    • 所以...很高兴您已经编辑了代码,但它现在可以工作了吗?然后关闭这个问题,让其他人知道答案是正确的。
    猜你喜欢
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 2014-03-15
    • 2019-01-17
    • 2012-07-25
    • 1970-01-01
    相关资源
    最近更新 更多