2016-08-13 56 views
1

我有一个函数:performSelector:onThread:withObject:waitUntilDone:不执行我的功能

-(void)doTask{ 
NSLog(@"do task start."); 
... 
} 

我想运行在另一个线程这个功能,这是我的尝试:

NSThread *workerThread = [[NSThread alloc] init]; 
[workerThread start]; 

[self performSelector:@selector(doTask) 
      onThread:workerThread 
      withObject:nil 
     waitUntilDone:NO]; 

当我运行它时,doTask函数没有执行。为什么?

+1

也许[此线程](http://stackoverflow.com/q/2584394/6541007)将有所帮助。 – OOPer

回答

0

定义selector到线程启动时运行:

NSThread* myThread = [[NSThread alloc] initWithTarget:self 
              selector:@selector(myThreadMainMethod:) 
               object:nil]; 
[myThread start]; // Actually create the thread 

和:

- (void)myThreadMainMethod:(id)object { 
    @autoreleasepool { 
     NSLog(@"do task start; object = %@", object); 
    } 
} 

请参阅Threading Programming Guide


对于它的价值,你应该使用大中央调度或操作队列,因为它使线程容易得多。请参阅并发编程指南的Migrating Away from Threads部分。

+0

是的,这个工程,我知道,但我想知道如何使它与我的代码一起工作?实际上,之前我使用过这个代码,现在出于复杂的原因,我需要先创建线程&start,然后在启动的线程上执行选择器。可能吗? –

+0

请参阅[设置运行循环](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15- SW25)和[何时使用运行循环?](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/ 10000057i-CH16-SW24)。 – Rob