Pregunta

Tengo un problema aquí...

Después de presionar un botón, quiero que se ejecute un bucle hasta que se alcance una condición:

- (IBAction)buttonclick1 ...

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

Me gustaría que se ejecutara un bucle hasta

((value2ForIf - valueForIf) >= 3)

y luego ejecute el código asociado con la declaración IF.

Lo que pretendo lograr es que el programa siga verificando si la afirmación anterior es cierta, antes de continuar con el código.Además de esto, hay una declaración else debajo de IF, aunque no sé si esto afectará un bucle.

No estoy seguro del formato del bucle requerido aquí y todo lo que he probado ha causado errores.Cualquier ayuda sería muy apreciada.

estu

¿Fue útil?

Solución

- (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:
  }
}

Otros consejos

En lugar de ejecutar un bucle estrecho, lo que bloquearía la ejecución de su aplicación a no ser que se ejecutan en otro hilo, se puede usar un NSTimer llamar a un método en un intervalo de tiempo de su elección y verificar el estado en ese método. Si se cumple la condición, puede invalidar el contador de tiempo y de continuar.

A partir de lo que se ha dicho, lo que quiere es un bucle while

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

Esto ejecuta el código en las llaves siempre que la diferencia en los valores es inferior a 3, lo que significa que se ejecutará hasta que su diferencia es 3 o mayor. Pero, como dijo Jasarien. Esta es una mala idea, ya que será el bloqueo de su programa. Si los valores están siendo actualizados por el propio código que está muy bien. Pero si están siendo actualizados por alguna interfaz de usuario del usuario, su bucle while bloqueará la interfaz de usuario y no permitir que el usuario ingresa nada.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top