@interface ThreadViewController : UIViewController {
UIProgressView *progressView;
UILabel *label;
NSThread *thr;
}
@property (nonatomic, retain) IBOutlet UIProgressView *progressView;
@property (nonatomic, retain) IBOutlet UILabel *label;
- (IBAction) startProgress:(id)sender;
@end
@implementation ThreadViewController
@synthesize progressView,label;
- (void)dealloc
{
[progressView release];
[label release];
[super dealloc];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.progressView = nil;
self.label = nil;
}
……
#define UPDATE_IN_MAINTHREAD 1
- (void) updateProgress:(id)arg
{
float currentValue = [progressView progress];
progressView.progress = currentValue + 0.01;
label.text = [NSString stringWithFormat:@".0f%%", progressView.progress*100];
NSLog(@"current value %f", currentValue);
}
- (void) beginDownload:(id)arg
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(@"begin to download ");
for (int i = 0; i < 100; i++) {
[NSThread sleepForTimeInterval:0.2f];
#if UPDATE_IN_MAINTHREAD
[self performSelectorOnMainThread:@selector(updateProgress:) withObject:nil waitUntilDone:NO];
#else
[self updateProgress:nil];
#endif
}
[pool release];
}
- (IBAction) startProgress:(id)sender
{
progressView.progress = 0.0f;
label.text = [NSString stringWithFormat:@".0f%%", progressView.progress*100];
NSLog(@"start progress");
#if 0
[NSThread detachNewThreadSelector: @selector(beginDownload:) toTarget:self withObject:nil];
#else
thr = [[NSThread alloc] initWithTarget:self selector:@selector(beginDownload:) object:nil];
[thr start];
#endif
}
@end