通过变量使UIAlertView触发

时间:2014-04-17 03:35:37

标签: ios objective-c uialertview

一些QR码扫描程序应用程序会在完成扫描后通过警报显示结果(URL或其他内容),因此我想做同样的事情并通过警报显示我的视频处理结果(整数)。我的视频处理功能是委托方法。我读了一些UIAlertView的例子,但需要按钮来触发警报。在我的情况下,需要在计算变量result后显示警报。但是,如果我在processImage函数中添加警报:

- (void)processImage:(cv::Mat&)image {
    int result;
    videoProcessing() {
    ...      
    result = 10
    }

    if (result == 10) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"The code is" message:@"10" 
        delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}    

我的应用因错误而终止:

2014-04-17 11:11:02.189 DotReader[3813:1803] *** Assertion failure in -[UIKeyboardTaskQueue performTask:], /SourceCache/UIKit/UIKit-2935.137/Keyboard/UIKeyboardTaskQueue.m:388
2014-04-17 11:11:02.190 DotReader[3813:1803] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue performTask:] may only be called from the main thread.'
*** First throw call stack:
(0x183ab6950 0x18ffbc1fc 0x183ab6810 0x1845eedb4 0x186aa8fc0 0x186aa8eec 0x186aa8b50 0x186aa6588 0x186aa565c 0x186f811d0 0x186f81698 0x186b00c7c 0x186affa04 0x186f83010 0x10007ad0c 0x10013c374 0x1827b8434 0x190594014 0x190593fd4 0x19059a4a8 0x1905964c0 0x19059b0f4 0x19059b4fc 0x1907296bc 0x19072954c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

有人能告诉我如何正确添加UIAlertView吗?

3 个答案:

答案 0 :(得分:3)

应该从主线程

调用所有UI事件
if (result == 10) {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"The code is" message:@"10"
                                                       delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    });

}

答案 1 :(得分:2)

我认为你在线程操作中调用警报。请尝试以下代码:

-(void)processImage:(cv::Mat&)image {
    int result;
    videoProcessing(){
    ...      
    result = 10
    }

    if(result == 10){
        [self performSelectorOnMainThread:@selector(showAlertMessage) withObject:nil waitUntilDone:YES];
    }
}   

-(void)showAlertMessage{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"The code is" message:@"10" 
        delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
} 

答案 2 :(得分:1)

试试这个:

-(void)processImage:(cv::Mat&)image {
    int result;
    videoProcessing() {
        ...      
        result = 10
    }

    if (result == 10) {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"The code is" message:@"10" 
            delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }];
    }
}

希望这有助于......:)