Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

nsthread

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.

like image 430
Mike S Avatar asked Mar 30 '12 02:03

Mike S


2 Answers

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...

like image 148
borrrden Avatar answered Nov 15 '22 09:11

borrrden


It seems like the easiest way would be to use blocks:

void (^now)(void) = ^ {
    NSDate *date = [NSDate date];
    NSLog(@"The date and time is %@", date);
};

and call:

now();

NSBlockOperation or dispatch_async().

See more here: http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1

like image 33
Matt Hudson Avatar answered Nov 15 '22 09:11

Matt Hudson