To create a new thread on iOS you can choose several different ways.

For those who come from unix programming and the C language, the first choice is, without any dubs, the use of the posix threads. In this case you don't have to change your code, all your existing code using the pthreads works fine.


If you want to use Cocoa and Objective-C you'll have different choices, IMHO the following one is the first you have to try to familiarize with Obj-C and threads.

multithread

 

Using NSThread Class

From the Apple Online documentation:

An NSThread object controls a thread of execution. Use this class when you want to have an Objective-C method run in its own thread of execution. Threads are especially useful when you need to perform a lengthy task, but don’t want it to block the execution of the rest of the application. In particular, you can use threads to avoid blocking the main thread of the application, which handles user interface and event-related actions. Threads can also be used to divide a large job into several smaller jobs, which can lead to performance increases on multi-core computers.

The NSThread class is part of the Foundation framework: /System/Library/Frameworks/Foundation.framework


First you have to write the method which will be your thread (for example a tcp server)

 

– (void)myServerThread {

    

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

    

TCPSERVER();

    

[pool release];

    

}

Note: if you are using ARC, the method becomes the following one:

 

– (void)myServerThread {

TCPSERVER();

}

 
Then, in a method of your application (for example, when the user tap an UIButton) you have to create the new thread:

 

– (IBAction)startServer:(id)sender

{

    ….

    [NSThread detachNewThreadSelector:@selector(myServerThread) withObject:nil];

    ….

}

 

At this point your brand new thread should be up and running. I want to add only one thing, it seems simple but it isn't! There are a lot of interesting pdf files over the internet, and apple provides a short manual to use thread with iOS. So be careful and RTFM (read the fantastic manuals).

 

Gg1.