开发者

How does one run multiple threads in objective c?

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 cal开发者_运维百科led the method in each thread?


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.


http://developer.apple.com/mac/library/documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008091


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜