Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

iphone - Show UIAlertView in background thread

I load data from a webservice in a background thread. Is it safe to show an UIAlertView in the background thread when anything goes wrong or should I show the alert view in the mainthread ?

thanks for the advice

Frank

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Never do anything with the GUI except from the main thread. It can cause very weird issues and or crashes you don't want to deal with. Usually the backtraces are also very unhelpful so try to avoid such issues by default.

Therefore use this:

[self performSelectorOnMainThread:@selector(showAlert:) withObject:alertString waitUntilDone:NO];

If you are using grand Central dispatch you could do something like:

dispatch_async(dispatch_get_main_queue(), ^{ /* show alert view */ });

Update:

Swift (3.0+):

DispatchQueue.main.async { // code }

It is sometimes helpful to do this with Notifications you receive as well, I have had instances where they were fired from a different thread.

Update 2:

It looks like apple has added some new tools coming in iOS11/Xcode9 to help debug issues where stuff is called on the incorrect thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...