Wednesday, April 17, 2013

NSThread example ios

[NSThread example] Following code fragment shows an NSThread example. It explains how to create a NSThread object and how to write target Thread Method. How to process screen display in thread run-loop. This NSThread example also demonstrates how to sleep the thead with NSThread:sleepForTimeInterval method.

// Creation Method 1.
//
[NSThread detachNewThreadSelector:@selector(_th) toTarget:self withObject:nil];

// Creation Method 2.
//
NSThread *thTime;
thTime = [[NSThread alloc] initWithTarget:self selector:@selector(_th) object:nil];
[thTime start];

// Implementation of main Thread Run-Loop.
//
- (void)_th {

 // Create auto release pool for the thread.
//

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

 // Check whether current thread is externally terminated or not.
while([[NSThread currentThread] isCancelled] == NO)    
{
NSLog(@"th 222");
NSString *t = [NSString stringWithFormat:@"%i", [lbText.text intValue] + 1];

  // Call main thread for displaying on the screen.
//
[self performSelectorOnMainThread:@selector(mainThreadSetText:) withObject:t waitUntilDone:YES];  

[NSThread sleepForTimeInterval:1.0];      // Sleep for a time.
}
[pool release];
}

//  Screen processing should be done outside the Thread.
- (void) mainThreadSetText:(NSString*)text
{
lbText.text = text;
}

- (void) _stop
{
[thTime cancel];
}