【问题标题】:UIAlertView Not showing from helper classUIAlertView 未从帮助程序类中显示
【发布时间】:2014-03-17 15:10:16
【问题描述】:

我正在尝试在函数助手类中使用方法:

函数助手:

+(void)ShowAlertViewWithTitle:(NSString *)title message:(NSString *)message{

    UIAlertView *alert = [[UIAlertView alloc]
                               initWithTitle:title
                                     message:message
                                    delegate:nil
                           cancelButtonTitle:@"Ok"
                           otherButtonTitles:nil, nil];
    [alert show];
}

这是一个静态函数,只有当我直接从ViewController调用它时才有效

但我需要的是从另一个类(不是 Viewcontroller)调用这个函数,然后它大部分时间都不会显示。

该类具有如下功能:

API 助手:

if (![FunctionHelper IsConnected]) {
   [FunctionHelper 
          ShowAlertViewWithTitle:@"Network connection error" 
                         message:@"Error!"];
}

编辑:

似乎问题在于我异步调用它。如何强制方法在主线程上调用它?

【问题讨论】:

  • +(void) ShowUIAlertView:(NSString *)title :(NSString *)message 这是一个错误的方法名称和参数。它应该类似于+ (void)ShowAlertViewWithTitle:(NSString *)title message:(NSString *)message
  • 你确定在主线程调用ShowUIAlertView
  • popeye 感谢您的建议,我将重命名,@Cy-4AH 你是对的,我正在异步调用此函数。如何强制它在主线程上运行

标签: ios objective-c methods static


【解决方案1】:
+ (void)ShowAlertViewWithTitle:(NSString *)title message:(NSString *)message{
    dispatch_async(dispatch_get_main_queue(), ^(){
        UIAlertView *alert = [[UIAlertView alloc]
                                   initWithTitle:title
                                         message:message
                                        delegate:nil
                               cancelButtonTitle:@"Ok"
                               otherButtonTitles:nil];
        [alert show];
    });
}

【讨论】:

  • +1 我还修改了方法名称以匹配问题,因为 OP 根据我的建议对其进行了更改。
  • 这对我有用,不需要确定按钮的任何点击逻辑,但现在我需要为确定按钮实现逻辑,我正在从 UIViewcontroller 子类调用这个辅助函数,如下所示 [[Helper sharedInstance ] ShowAlertViewWithTitle:@"Error" message:@"foo"];
  • @Edwin,您可以添加 UIAlertView 的委托作为方法参数或使用其他一些委托作为您的逻辑。
猜你喜欢
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多