iOS 在点击带有分配的 IBAction (UIButton) 的 IBOutlet 后,应用程序无一例外地崩溃

iOS app crashes without any exception after tapping IBOutlet with assigned IBAction (UIButton)

我的任务是使用多行文本输入字段创建自定义 UIAlertView,并且一切正常,直到我需要在点击关闭按钮时执行一些操作。作为示例,我正在使用:http://iphonedevelopment.blogspot.co.uk/2010/05/custom-alert-views.html

出于测试目的,我创建了非常简单的弹出窗口。基本上它是带有单个按钮的 UIViewController xib。主要class演示如下:

#import "testViewController.h"

@interface testViewController ()

@end

@implementation testViewController

- (id)init
{
    self = [super initWithNibName:@"testViewController" bundle:nil];

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showInView:(UIView *)view
{
    [view addSubview:[self view]];
    [[self view] setFrame: [view bounds]];
    [[self view] setCenter:[view center]];
}

- (IBAction)onTap:(id)sender {
    NSLog(@"All OK");
}

@end

然后在根 UIViewController 中调用我的自定义警报:

- (IBAction)showAlert:(id)sender
{
    dispatch_async(dispatch_get_main_queue(), ^{
        testViewController *alert = [[testViewController alloc] init];
        [alert showInView:[self view]];
    });
}

到目前为止,我已经尝试过主线程或全局队列甚至同步调度,但一切都以中断结束:

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); <-- Thread 1:EXC_BAD_ACCESS (code=1, address=0xa000000c)
    }
}

尝试为按钮添加观察者,但还是不行..

非常感谢任何帮助

检查您的 UIButton 是否分配了多个 IBoutlets 或多个 IBActions。这是一个常见问题,有时会在我们没有通知的情况下发生。

原来我的testViewController在我点击按钮之前被ARC释放了

这就是幸福"if you want to add one viewcontroller view to other viewcontroller's view then after adding of views you should convey to the compiler that second view controller is going to be child to the first"

即必须预先暗示亲子关系。

现在只需使用以下内容修改您的 showAlert 方法。它正在 100% 工作。

- (IBAction)showAlert:(id)sender {

    dispatch_async(dispatch_get_main_queue(), ^{
        testViewController *alert = [[testViewController alloc] init];
        [alert showInView:[self view]];

        [self addChildViewController:alert];
        [alert didMoveToParentViewController:self];
    });
}