iphone中的多个线程

时间:2010-09-01 12:30:02

标签: objective-c

如何在iphone中创建多个线程(单个类)

请帮我提供示例代码。

2 个答案:

答案 0 :(得分:0)

查看NSThreadNSOperationQueue的文档以及为performSelector...定义的各种NSObject方法。

答案 1 :(得分:0)

NSThread Class reference

运行子线程的示例:

- (void)threadRun
{
  // One thread, one autorelease pool. as main thread's pool inside main.c
  NSAutoreleasePool *aPool = [[NSAuroreleasePool alloc] init];

  // do-job in thread here

  [aPool release];
}

- (void)performJobWithThread
{
    // Method 1:
    NSThread *aThread = [[NSThread alloc] initWithTarget:self 
                                          selector:@selector(threadRun)
                                          object:nil];

    [aThread start];

    /// Release aThread at some point avoid memory leak.

    // Method 2:
    [NSThread detachNewThreadSelector:@selector:@selector(threadRun)
                             toTarget:self
                             withObject:nil];
}

在使用NSThread之前,最好先阅读Threading Programming Guide。它会告诉你有关内存管理,与其他线程的通信,......等等。

NSOperation和NSOperationQueue很适合设计多线程。但我现在正在学习它们,我无法清楚地谈论它们。