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?
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?
You could use NSOperationQueue. I'm not sure what versions of iOS it works with, though.
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.