Reputation: 2439
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.
Upvotes: 0
Views: 2101
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
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