Create new thread
Sometimes you might need to open a new thread on an iPhone or iPad app. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straightforward method to open a new thread.
Strategy to open a new thread is fairly simple: First, we need to create the new thread. Second, we need instantiate a new thread. Third, we need to start the new thread.
Here are actual code samples:
The first thing you need to do is to create a new method that will execute in the new thread. In this example, we will just have a message shown on the console
1 - ( void ) newMethod 2 { 3 NSLog(@"Executing new thread."); 4 }
Then you need to create a new thread using NSThread. The someMethod is the method name you want to run in the new thread :
1 NSThread * thread ; 2 thread = [ [ NSThread alloc] initWithTarget : self 3 selector : @selector( someMethod ) 4 object : nil ] ;
Finally, you need to start the new thread with the following line :
1 [ thread start ] ;
So, this is how a final code for creating and running a new thread will look like:
1 NSThread * thread ; 2 thread = [ [ NSThread alloc] initWithTarget : self 3 selector : @selector( someMethod ) 4 object : nil ] ; 5 [ thread start ] ; 6 ... 7 - ( void ) newMethod 8 { 9 NSLog(@"Executing new thread."); 10 }