Jean Paul
Jean Paul

Reputation: 2439

Using NSThread in this code piece

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.

  1. Its just calling a method. Why is NSThread used here?
  2. 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?

Upvotes: 0

Views: 2101

Answers (2)

Nick Lockwood
Nick Lockwood

Reputation: 40995

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:

[self performSelectorInBackground:@selector(myMethod) withObject:nil];

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:

[NSThread detachNewThreadSelector:@selector(methodA) toTarget:self withObject:nil];
[self methodB];

Then methodA and methodB will be running at the same time and there is no guarantee that methodA will finish before methodB.

Upvotes: 3

basvk
basvk

Reputation: 4546

I always use NSThread detachNewThreadSelector in combination with an auto-release pool, like so:

  -(void)myMethod {
      NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
      // .. Do stuff in this thread
      [pool release];
  };

If you want to "simply" perform a selector, do it like this:

  [self performSelector:@selector(myMethod)];

Upvotes: 2

Related Questions