How do I create an NSThread that isn't the main thread without performing a selector immediately

Mike S picture Mike S · Mar 30, 2012 · Viewed 10.9k times · Source

I want to create a worker thread that isn't the main thread so I can call ...

[self performSelector:@selector(doStuff) OnThread:self.myWorkerThread withObject:nil];

... in a bunch of locations in my code. How do I create a thread.. any thread and assign it to a variable so I can use it over and over in my code. NSThread detachNewThreadWithSElector will only create one for the purpose of running that one selector. I need to create a thread and use it somehow.

I am using iOS and need to perform all my CoreData writes on a writerThread. I need to use the same thread (that isn't the main one) every time.

Answer

borrrden picture borrrden · Mar 30, 2012

I highly recommend looking into Grand Central Dispatch instead :). You can easily create a dispatch queue via dispatch_queue_create or get one of the existing concurrent threads and send whatever you want to it. It will create the appropriate number of threads based on the workload / OS status, etc. It will look like this:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    //Do stuff
});

Or you can look into its NS counterpart, NSOperation. I don't know of a way to do this with just NSThread. It seems the only way to set its selector is to init it with one.

EDIT If you want just a thread, just call [[NSThread alloc] init] :p

FURTHER EDIT: iPhone: how to use performSelector:onThread:withObject:waitUntilDone: method?

As per this answer, it is going to be difficult to set up, as every thread needs a "main" function at the time it is created or else it will do nothing...