performSelector:onThread:withObject:waitUntilDone:不执行我的函数

时间:2016-08-13 09:22:32

标签: ios objective-c nsthread

我有一个功能:

-(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 个答案:

答案 0 :(得分: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

对于它的价值,您可能应该使用Grand Central Dispatch或操作队列,因为它使线程更容易。请参阅并发编程指南的Migrating Away from Threads部分。