How do I update a progress bar in Cocoa during a long running loop?

后端 未结 4 530
悲&欢浪女
悲&欢浪女 2020-12-29 00:17

I\'ve got a while loop, that runs for many seconds and that\'s why I want to update a progress bar (NSProgressIndicator) during that process, but it updates onl

4条回答
  •  离开以前
    2020-12-29 00:38

    If you are building for Snow Leopard, the easiest solution is in my opinion to use blocks and Grand Central Dispatch.

    The following code shows you how your startIt: method would look like when using GCD.

    Your stopIt: method should work fine as you wrote it. The reason why it wasn't working before is that mouse events happen on the main thread and thus the button didn't respond to you because you were doing work on the main thread. This issue should have been resolved now as the work has been put on a different thread now with GCD. Try the code, and if it doesn't work, let me know and I will see if I made some errors in it.

    // This method runs when a start button is clicked.
    - (IBAction)startIt:(id)sender {
    
        //Create the block that we wish to run on a different thread.
        void (^progressBlock)(void);
        progressBlock = ^{
    
        [progressbar setDoubleValue:0.0];
        [progressbar startAnimation:sender];
        running = YES; // this is a instance variable
    
        int i = 0;
        while (running) {
            if (i++ >= processAmount) { // processAmount is something like 1000000
                running = NO;
                continue;
            }
    
            // Update progress bar
            double progr = (double)i / (double)processAmount;
            NSLog(@"progr: %f", progr); // Logs values between 0.0 and 1.0
    
            //NOTE: It is important to let all UI updates occur on the main thread,
            //so we put the following UI updates on the main queue.
            dispatch_async(dispatch_get_main_queue(), ^{
                [progressbar setDoubleValue:progr];
                [progressbar setNeedsDisplay:YES];
            });
    
            // Do some more hard work here...
        }
    
        }; //end of progressBlock
    
        //Finally, run the block on a different thread.
        dispatch_queue_t queue = dispatch_get_global_queue(0,0);
        dispatch_async(queue,progressBlock);
    }
    

提交回复
热议问题