I am working on someone else’s code. I came across a line of code
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
I have 2 questions to ask.
- Its just calling a method. Why is NSThread used here?
- While running the code, On some instances, this method doesn’t get called. When I put a breakpoint inside the method, it always get called. But if I remove the breakpoint, on some instances the method doesn’t get called. Is this the problem of NSThread?
Using NSThread in this way means that the method “myMethod” is being called on a background thread, concurrently with the rest of the code. It is equivalent to this, which you may also have seen:
If the method is not getting called (or seeming to not get called), it may be down to concurrency issues, i.e. the fact that the execution order of that method and ones you call after in on the main thread is not guaranteed, so you are expecting it to be called earlier than it actually is.
If you say:
Then methodA and methodB will be running at the same time and there is no guarantee that methodA will finish before methodB.