Re: How to run progress bar in a separate thread
Re: How to run progress bar in a separate thread
- Subject: Re: How to run progress bar in a separate thread
- From: James Hober <email@hidden>
- Date: Mon, 10 Mar 2008 23:41:15 -0700
The following runs your progress indicator modally, which means the
user can't do anything while it runs. You may or may not want that
behavior.
It uses a timer to update the progress indicator on the main thread
by reading some instance variables. Your secondary thread writes to
those instance variables as it does its time intensive task. Since
one thread writes and the other reads and the precise order these
happen doesn't matter much, you can get away with not locking:
@interface Progress : NSObject {
double _percentDoneTimeIntensiveActivity;
BOOL _doneTimeIntensiveActivity;
IBOutlet NSProgressIndicator *_progressIndicator;
}
@end
@implementation Progress
const NSTimeInterval PROGRESS_INDICATOR_TIMER_INTERVAL = 0.05; //
seconds between progress updates
- (IBAction)yourButtonGotClicked:(id)sender
{
[NSThread detachNewThreadSelector:@selector
(doTimeIntensiveActivity)
toTarget:self
withObject:nil];
NSTimer *timer = [NSTimer
timerWithTimeInterval:PROGRESS_INDICATOR_TIMER_INTERVAL
target:self
selector:@selector
(updateProgressIndicator:)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer
forMode:NSModalPanelRunLoopMode];
[NSApp runModalForWindow:[_progressIndicator window]]; //shows
and centers the window
}
- (void)updateProgressIndicator:(NSTimer *)aTimer
{
if (! _doneTimeIntensiveActivity)
{
[_progressIndicator
setDoubleValue:_percentDoneTimeIntensiveActivity];
} else {
[_progressIndicator setDoubleValue:1.0];
[aTimer invalidate]; //the run loop will release aTimer
[NSApp abortModal];
}
}
- (void)doTimeIntensiveActivity
{
//separate thread needs its own autorelease pool
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
//do your time intensive activity while
//periodically setting _percentDoneTimeIntensiveActivity to a
value between 0.0 and 1.0
//when your time intensive activity is done, set
_doneTimeIntensiveActivity = YES
[pool release];
}
@end
James
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden