1

I have a function:

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

I want to run this function on another thread, this is what I tried:

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

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

when I run it, the doTask function is not executed. WHY?

Jay Bhalani
  • 4,142
  • 8
  • 37
  • 50
Leem.fin
  • 40,781
  • 83
  • 202
  • 354

1 Answers1

0

Define the selector to run when the thread starts:

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

And:

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

Please refer to the Threading Programming Guide.


For what it's worth, you probably should be using Grand Central Dispatch or operation queues, as it makes threading much easier. See the Migrating Away from Threads section of the Concurrency Programming Guide.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Yes, this works, I know, but I am wondering how can I make it work with my code? Actually, I was using this code before, now for complex reason, I need to create thread & start first , then perform selector on the started thread. Is it possible? – Leem.fin Aug 13 '16 at 09:41
  • See [Setting Up a Run Loop](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW25) and [When Would I Use a Run Loop?](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW24). – Rob Aug 13 '16 at 09:53