开发者

Show UIAlertView in background thread

开发者 https://www.devze.com 2023-02-14 08:19 出处:网络
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 ?

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开发者_如何学Python advice

Frank


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.


dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        });

this code works for me


You could try showing the alert on the main thread by:

UIAlertView *alert = [
    [[UIAlertView alloc] initWithTitle:@"the title"
                               message:@"the message"
                              delegate:self
                     cancelButtonTitle:@"OK"
                     otherButtonTitles: nil] autorelease];
[alert performSelector:@selector(show)
              onThread:[NSThread mainThread]
            withObject:nil
         waitUntilDone:NO];
[alert release];
0

精彩评论

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

关注公众号