闪烁的屏幕,虽然我在主线程上做我的警报

时间:2013-04-18 12:19:55

标签: ios multithreading uialertview

我知道UIKit的东西应该在mian线程上完成,这就是为什么,我确保我的警报视图显示在主线程上。

-(void)showAlert:(NSString *)alertMessage{

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

}

但是,当我关闭警报时,屏幕会闪烁。所以这没有解决我的问题,我错过了什么?

3 个答案:

答案 0 :(得分:0)

如果您从后台线程调用show alert方法,请尝试使用

    [self performSelectorOnMainThread:@selector(showAlert:) withObject:alertMessage waitUntilDone:YES];

用于方法调用并将showAlert方法更改为

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMessage message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];

答案 1 :(得分:0)

为什么不将UIAlertView分配到主线程?还有你的解决方案,你有内存泄漏。试试这个:

-(void)showAlert:(NSString *)alertMessage{


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

}

在您的情况下,“OK”文本实际上应该是取消按钮。

答案 2 :(得分:0)

将以下代码写入您希望在msgDict中显示带有相应标题和消息的UIAlertView的位置。

    NSMutableDictionary *msgDict=[[NSMutableDictionary alloc] init];
    [msgDict setValue:@"Title for AlertView" forKey:@"Title"];
    [msgDict setValue:@"Message within the AlertView" forKey:@"Message"];

    [self performSelectorOnMainThread:@selector(showAlert:) withObject:msgDict  
                        waitUntilDone:YES];

程序控制到达showAlert方法然后

    -(void)showAlert:(NSMutableDictionary *)msgDict
      {
           UIAlertView *alert=[[UIAlertView alloc] 
                       initWithTitle:[NSString stringWithFormat:@"%@",[msgDict objectForKey:@"Title"]] 
                             message:[NSString stringWithFormat:@"%@",[msgDict objectForKey:"Message"]]
                            delegate:nil 
                   cancelButtonTitle:nil 
                   otherButtonTitles:@"OK", nil];
           [alert show];
      }