performSelector:onThread: in Swift?
Asked Answered
S

1

7

In a current iOS app I am using this perform selector approach:

[self performSelector:@selector(doSomething)
             onThread:myThread
           withObject:nil
        waitUntilDone:NO
                modes:[NSArray arrayWithObject:NSRunLoopCommonModes]];

I am not sure how to make a selector run on a specific thread in swift. Any suggestions?

Siamese answered 2/7, 2014 at 22:4 Comment(3)
@rickster: I don't want to create a thread. I want to tell to run a specific function on a specific thread.Siamese
@Jack Wu: Swift alternative to performSelectorOnMainThread does not tell us how to tell a function to run on a specific thread. It uses queues instead.Siamese
Stack Overflow can go ahead and do whatever they want with this question. IT IS NOT A DUP. I gave the reasons above. None of the people that marked this as a duplicate actually understand it. I am talking about performSelector:onThread. The "onThread" word in there is what none of the these guys understand. None of the answers they provided tell us how to target a specific thread that is not the main thread. So, unfortunately this questions stays as is hoping that somebody can actually answer it. IT IS NOT A DUPLICATE.Just because somebody doesn't understand it it doesn't mean it's a dup.Siamese
K
8

As I suggested in comment, you shouldn't manage threads any more. Always use dispatch_queue instead of threads.

If you somehow really want to do it, here is a workaround: CFRunLoopPerformBlock.

This is C code, but I think you can translate it to Swift code without too much work.

// worker thread
CFRunLoopRef myrunloop; // some shared variable

void worker_thread_main() {
    myrunloop = CFRunLoopGetCurrent();
    CFRunLoopRun(); // or other methods to run the runloop    
}

// other thread to schedule work

CFRunLoopPerformBlock(myrunloop, kCFRunLoopCommonModes, ^{
    dowork();
});
Kalamazoo answered 3/7, 2014 at 22:42 Comment(1)
thanks for the example. I'll try to see if I can get this into swift and then see if it does the trick. I agree about the queue, you are for sure correct on that. In the situation I'm in I am in need to target a thread. Thank you.Siamese

© 2022 - 2024 — McMap. All rights reserved.