我有一個while
循環,它運行了很多秒,這就是爲什麼我想在該過程中更新進度條(NSProgressIndicator),但在循環完成後只更新一次。順便說一句,如果我想更新標籤文本,也會發生同樣的情況。如何在長時間運行的循環中更新可可中的進度條?
我相信,我的循環可以防止該應用程序的其他事情發生。必須有另一種技術。這是否與線程或某事有關?我在正確的軌道上嗎?有人能給我一個簡單的例子,如何「優化」我的應用程序?
我的應用程序是一個Cocoa應用程序(的Xcode 3.2.1),在我Example_AppDelegate.m
這兩種方法:
// This method runs when a start button is clicked. - (IBAction)startIt:(id)sender { [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 [progressbar setDoubleValue:progr]; [progressbar needsDisplay]; // Do I need this? // Do some more hard work here... } } // This method runs when a stop button is clicked, but as long // as -startIt is busy, a click on the stop button does nothing. - (IBAction)stopIt:(id)sender { NSLog(@"Stop it!"); running = NO; [progressbar stopAnimation:sender]; }
我真的很新的Objective-C,可可和應用程序的UI。非常感謝您提供有用的答案。
非常感謝,我給這是一個嘗試這個週末! – Nick 2010-03-26 10:10:59
這就是我一直在尋找的。工作正常,這給了我一個很好的起點來了解更多。謝謝! – Nick 2010-03-30 22:56:58
感謝您的Enchilada!我剛剛學到了一些我不知道的東西!非常興奮地發現關於塊和GCD! – 2011-08-24 02:14:22