NStimer和for循环

时间:2011-02-20 08:28:18

标签: iphone loops for-loop nstimer

我正在努力解决这个问题。我看到了一些可以执行此操作的代码:

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

然后在doActions中调用它。

问题是我想在按下按钮时调用它,并且操作是IBaction。我一直在sigAbrt

有人可以给我一些示例代码,您可以在按下按钮的同时每隔1秒将标签从“打开”更改为“关闭”吗?

修改

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

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

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

2 个答案:

答案 0 :(得分:1)

我仍然不清楚,你想要完成什么:如果你只是简单地用简单的英语写下来,我会发现很多更容易。< / p>

那就是说,这就是我认为会让你到达目的地的地方:

// 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...

答案 1 :(得分:0)

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

- (void) doActions {
theLabel.hidden != theLabel.hidden;
}