views:

60

answers:

3

I have some code which runs in a timer, but I would like to have a few of these run simultaneously.

How are threads run in objective c?

Can I put the current code in a method, and just start up threads and called the method in each thread?

+1  A: 

You could use NSOperationQueue. I'm not sure what versions of iOS it works with, though.

David
+2  A: 

The direct answer is yes: Use NSThread The you can do something like this:

 [NSThread detachNewThreadSelector:@selector(myThreadMethod:) toTarget:self withObject:someOptions];

This will create a new Thread and call some method you define on some object. A common pitfall is that in a thread you need to create a separate NSAutoreleasePool if you're not using Garbage Collection. In this case above it might look like this:

- (void)myThreadMethod:(id)options
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    ... // your method contents here

    [pool release];
}

However, as others pointed out already, threads should be no longer used. They were sorta replaced by NSOperations, or Blocks and GrandCentralDispatch.

Max Seelemann
Saying threads should no longer be used is incorrect. Whether you are using NSThread, NSOperationQueue, performSelectorInBackground, pthreads, blocks, or the gcd APIs, under the hood it all boils down to the kernel running additional threads.
rpetrich
right, you should not use them directly, that's what I meant. You should stick to a higher level of abstraction, like operation queues or blocks...
Max Seelemann