call a function using thread in xcode

Subrat nayak. picture Subrat nayak. · May 3, 2012 · Viewed 17.9k times · Source

i have created a thread in xcode and i have given the function name to be called from that thread. but my problem is that the function name which is given to call is not being called(came to know when put a breakpoint in that function)

code:

 NSThread* myThread; 
 [myThread start]; 
 [self performSelector:@selector(func1:) onThread:myThread withObject:nil waitUntilDone:false]

and later i tried this one also:

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

above func1 is the name of the function to be called.

so can any one please tell me how to create the thread and call func1 from there....

Answer

mttrb picture mttrb · May 3, 2012

In your first code sample it doesn't look like you are actually creating a new thread. You create an empty myThread variable and then call start on it but this will just result in start being sent to nil. The empty thread variable is then sent to the performSelector:onThread:withObject:waitUntilDone: method which will presumably do nothing.

You will need to properly create a thread before you can actually run something on it using performSelector:onThread:withObject:waitUntilDone:.

Alternatively, it would be much easier, assuming you don't care which background thread the method runs on, to simply use performSelectorInBackground:withObject:. For example:

[self performSelectorInBackground:@selector(func1:) withObject:nil];