2

我是 ios 的初学者,我有两个按钮,btn1 和 btn2。

function1:我将这个功能用于我的button1,当点击它时我有指令要做。

function2:我将此功能用于我的button2,当单击它时我想更改globalVar为1以停止循环(whilefunction1

-(IBAction)function1
{

while ( globalVar==0 )
{
    //instruction
}

}

-(IBAction)function2
{
globalVar = 1;
}

但它不起作用。

4

5 回答 5

2

That won't work as you are blocking the UI thread with:

while ( globalVar == 0 )    // I assume you meant == and not =
{
    //instruction
}

as no UI events can be processed.

Tell us what you actually want to do and I can perhaps provide more of a solution.

于 2013-09-27T16:06:13.793 回答
1

让您的 while 循环在后台异步运行:

-(IBAction)function1
{
    dispatch_queue_t backgroundQueue = dispatch_queue_create("loopy-loop-background-queue", NULL);
    dispatch_async(backgroundQueue, ^(void) {

        while ( globalVar==0 )
        {
            //instruction
            _globalCount++;

            if( (_globalCount % 10) == 0)
            {
                [self performSelector:@selector(updateDisplay:)];
            }
        }

    });
}

请记住将任何 UI 更新放回主队列:

-(void)updateDisplay:(id)sender
{
    dispatch_async(dispatch_get_main_queue(), ^(void) {

        self.outletTimerLabel.text = [NSString stringWithFormat:@"%d", _globalCount];
        [self.outletTimerLabel setNeedsDisplay];

    });
}
于 2013-09-28T02:14:23.810 回答
0

最后我找到了我的问题的解决方案。下面的代码是解决方案

- (IBAction)function1
{

    dispatch_queue_t backgroundQueue = dispatch_queue_create("loopy-loop-background-queue", NULL);
    dispatch_async(backgroundQueue, ^(void) {

        while ( _globalVar==0 )
        {
            //instruction
            _globalCount++;
            NSLog(@"aaa");

            if( (_globalCount % 10) == 0)
            {
                [self performSelector:@selector(function2)];
            }
        }

    });
}

-(IBAction)function2
{
    if (_stop!=0)
    {
        _globalVar=1;
    }
    dispatch_async(dispatch_get_main_queue(), ^(void)
    {

        self.outletTimerLabel.text = [NSString stringWithFormat:@"%d", _globalCount];
        [self.outletTimerLabel setNeedsDisplay];

    });
}

-(IBAction)function3
{
    dispatch_async(dispatch_get_main_queue(), ^(void)
                   {

                       _stop=1;

                   });
}
于 2013-09-28T09:12:17.527 回答
0

这应该这样做。

-(IBAction)function1
{


   NSRunLoop *theRL = [NSRunLoop currentRunLoop];
   while ( globalVar==0 && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]])
   {
       //instruction
   }

}

-(IBAction)function2
{
globalVar = 1;
}
于 2013-09-27T20:32:57.527 回答
-2
-(IBAction)function1
{

    while ( globalVar==0 )
    {
      //instruction
    }

}

-(IBAction)function2
{
   globalVar = 1;
   [self function1]; // goto
}
于 2013-09-27T20:35:34.763 回答