0

我这里有问题...

按下按钮后,我希望循环运行直到达到条件:

- (IBAction)buttonclick1 ...

if ((value2ForIf - valueForIf) >= 3) { ...

我想要一个循环运行直到

((value2ForIf - valueForIf) >= 3)

然后执行与 IF 语句关联的代码。

我的目标是让程序在继续代码之前继续检查上述语句是否正确。除此之外,在 IF 下方还有一条 else 语句,虽然我不知道这是否会影响循环。

我不确定此处所需的循环格式,并且我尝试过的所有操作都导致了错误。任何帮助将不胜感激。

斯图

4

3 回答 3

2

您可以使用 NSTimer 在您选择的时间间隔内调用一个方法并检查该方法中的条件,而不是运行一个紧密的循环,这会阻止您的应用程序的执行,除非在另一个线程上运行。如果满足条件,您可以使计时器无效并继续。

于 2009-11-16T00:38:41.423 回答
2
- (IBAction)buttonclick1 ...
{
  //You may also want to consider adding a visual cue that work is being done if it might
  //take a while until the condition that you're testing becomes valid.
  //If so, uncomment and implement the following:

  /*
   //Adds a progress view, note that it must be declared outside this method, to be able to
   //access it later, in order for it to be removed
   progView = [[MyProgressView alloc] initWithFrame: CGRectMake(...)];
   [self.view addSubview: progView];
   [progView release];

   //Disables the button to prevent further touches until the condition is met,
   //and makes it a bit transparent, to visually indicate its disabled state
   thisButton.enabled = NO;
   thisButton.alpha = 0.5;
  */

  //Starts a timer to perform the verification
  NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 0.2
                            target: self
                            selector: @selector(buttonAction:)
                            userInfo: nil
                            repeats: YES];
}


- (void)buttonAction: (NSTimer *) timer
{
  if ((value2ForIf - valueForIf) >= 3)
  {
    //If the condition is met, the timer is invalidated, in order not to fire again
    [timer invalidate];

    //If you considered adding a visual cue, now it's time to remove it
    /*
      //Remove the progress view
      [progView removeFromSuperview];

      //Enable the button and make it opaque, to signal that
      //it's again ready to be touched
      thisButton.enabled = YES;
      thisButton.alpha = 1.0;
    */

    //The rest of your code here:
  }
}
于 2009-11-16T09:08:11.993 回答
1

根据您所说,您想要的是一个while循环

while( (value2ForIf - valueForIf) < 3 ) { ...Code Here... }

只要值的差异小于 3,这将运行大括号中的代码,这意味着它将运行直到它们的差异为 3 或更大。但正如贾萨里恩所说。这是一个坏主意,因为您将阻止您的程序。如果值由代码本身更新,那很好。但是,如果它们被用户的某些 UI 更新,您的 while 循环将阻止 UI 并且不允许用户输入任何内容。

于 2009-11-16T00:41:28.847 回答