Showing posts with label NSThread example. Show all posts
Showing posts with label NSThread example. Show all posts

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];
}

Monday, May 9, 2011

NSThread Example 3

NSThread creation example by NSThread alloc and init.

NSThread *myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadFunc:) object:nil];
[myThread start];


Simple enough!

Friday, May 6, 2011

Background method execution using NSThread code example objc

You can execute a method in background mode using detachNewThreadSelector method. For proper memory management, the target method maintains its own AutoreleasePool. [detachNewThreadSelector]


[NSThread detachNewThreadSelector:@selector(doSomethingInBack:) toTarget:self withObject:nil];

-(void) doSomethingInBack:(id)anObject {
NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
// 다른 스레드로 실행할 코드 작성.p
[NSThread exit];
// 메모리 릭 방지.
[autoreleasepool release];
}