开发者

iphone - what is the logic of this kind of multithread operation

I am just trying to understand this: multithread is a way of firing a method in another thread, so it will not hang the main thread (when something heavy must be done). But I have seen stuff like this:

this goes on the main code:

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

and here goes the thread

-(void) createNewThread {

NSAutoreleasePool* p = [[NSAutoreleasePool alloc] init];

[self performSelectorOnMainThread:@selector(doSomeStuff) withObject:nil waitUntilDone:YES];

[p release];
}

My problem with this is: if the thread is intended to relieve the main thread from doing something, why is doSomeStuff being called using performSelectorO开发者_高级运维nMainThread? Isn't that insane? I mean, you fire a second thread just to run something on the main thread, a thread that in fact you shouldn't be using.

I have seen a lot of code on the web write this way.

I know that probably it is done that way because it is doing something that is not thread safe, but is doing this really useful? To me sounds that it is totally useless and it would be better to do something like

[self performSelector:@selector(doSomeStuff) withObject:nil afterDelay:0.01];

what do you guys think? thanks in advance.


performSelectorOnMainThread:withObject:waitUntilDone: puts the call on a queue to perform on the next iteration of the run loop. performSelector:withObject:afterDelay: sets up a timer to perform the action. However, creating a new thread to call performSelectorOnMainThread makes no sense because it puts the call on the queue even if it is already on the main thread.


If that's the entire body of the createNewThread method then it makes no sense. But if other stuff actually happens in createNewThread then there might be a good reason. The most common scenario for having a background thread use performSelectorOnMainThread: is if the UI needs to update as a result of the background activity. Like if you're processing a large data set and you want to show the user how much progress has been made so far. UIKit is not thread-safe so you can't update the UI from the background thread. But you might do something like, have the background doing a lot of work in a loop, and at every pass through the loop (or every 5, or whatever) call back to the main thread to update the UI. This makes the code switch back to the main loop just long enough to update the UI before returning to the background for the heavy duty work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜