UIAlertView在块内时崩溃

时间:2013-11-25 20:54:05

标签: ios ios7 uialertview objective-c-blocks

我有一个带UIAlertView的块,我想在点击OK后运行一些代码。

- (IBAction)connectToAccount:(UIButton *)sender {


        void (^block) (FTjsonRecords *obj, NSError *error) = ^(FTjsonRecords *obj, NSError *error) {


                [self updateInterfaceWithReachability:self.hostReachability];

                    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Success!"
                                                                 message:@"Online sync is now enabled."
                                                                delegate:self
                                                       cancelButtonTitle:@"OK"
                                                       otherButtonTitles:nil];
                    [av show];


        };

        [sync checkFirstLogin:email viaPassword:password viaCompletion:block];
    }

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    [[self navigationController] popToRootViewControllerAnimated:NO];
    NSNotification *note = [NSNotification notificationWithName:IOS_SWITCH_TAB object:nil];
    [[NSNotificationCenter defaultCenter] postNotification:note];
}

当我点击确定时,该应用程序崩溃,没有任何例外,以便跟进。 我不知道该怎么办。建议会很棒。感谢

更新

我在[av show];上设置了一个断点,线程如下:

enter image description here

3 个答案:

答案 0 :(得分:1)

由于所有UI代码都必须在主线程中运行,因此您需要将警报代码括在dispatch_async块中,如下所示:

dispatch_async(dispatch_get_main_queue(), ^{
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Success!"
                                                 message:@"Online sync is now enabled."
                                                delegate:self
                                       cancelButtonTitle:@"OK"
    [av show];
});

答案 1 :(得分:1)

我终于找到了问题所在。因为它被认为是一个线程问题,我首先无法发现。

在行中:

[self updateInterfaceWithReachability:self.hostReachability];

我在异步线程上做了一些工作,最后我调用了一个

[[self navigationController] popToRootViewControllerAnimated:YES];

当我显示弹出窗口并且两个相撞时,发生了这种情况。我从popToRootViewControllerAnimated中删除了updateInterfaceWithReachability并将其放入UIAlertView的委托中,现在它按预期工作。

我希望在类似的情况下,这会对其他人有所帮助。

答案 2 :(得分:0)

还值得考虑的是UIAlertView的内存管理。如果UIAlertView在可见时重新分配,它也会导致崩溃。