Monday, May 9, 2011

NSThread Example objc

An NSThread example collected from http://iphoneappsmaker.tistory.com/516
When startThreadButtonPressed method is invoked, a new NSThread object is
created and detached with startTheBackgroundJob callback. This method
simples updates the progressbar. [NSThread Example]




- (IBAction) startThreadButtonPressed:(UIButton *)sender {

threadStartButton.hidden = YES;
threadValueLabel.text = @"0";
threadProgressView.progress = 0.0;
[NSThreaddetachNewThreadSelector:@selector(startTheBackgroundJob) toTarget:selfwithObject:nil];

}

- (void)startTheBackgroundJob {

NSAutoreleasePool *pool = [[NSAutoreleasePoolalloc] init];
// wait for 3 seconds before starting the thread, you don't have to do that. This is just an example how to stop the NSThread for some time
[NSThreadsleepForTimeInterval:3];
    [selfperformSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nilwaitUntilDone:NO];
    [pool release];

}

- (voidmakeMyProgressBarMoving{

    
float actual = [threadProgressViewprogress];
threadValueLabel.text = [NSStringstringWithFormat:@"%.2f", actual];
if (actual < 1) {
threadProgressView.progress = actual + 0.01;
[NSTimerscheduledTimerWithTimeInterval:0.5target:selfselector:@selector(makeMyProgressBarMoving) userInfo:nilrepeats:NO];
}
elsethreadStartButton.hidden = NO;

}