Make UIAlertView blocking

后端 未结 5 2043
刺人心
刺人心 2020-12-03 12:49

I need make UIAlertView blocking. Because i have function and i need to return UIAlertView choice. But problem is that after UIAlertView

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 12:59

    I just found this question by accident and even by entering Apple hell by posting this, I hereby proclaim this as a proof of concept:

    @interface EvilShitClass () 
    @end
    
    @implementation EvilShitClass {
        BOOL _isCanceled, _wasYes;
    }
    

    Here is the static method for a yes/no query:

    + (BOOL)yesNoQueryWithTitle:(NSString*)title text:(NSString*)text {
    
        EvilShitClass *shit = [EvilShitClass new];
        UIAlertView *alertView = [UIAlertView new];
        alertView.delegate = shit;
        alertView.title = title;
        alertView.message = text;
        [alertView addButtonWithTitle:@"Yes"];
        [alertView addButtonWithTitle:@"No"];
    
        NSRunLoop *run_loop = [NSRunLoop currentRunLoop];
    
        [alertView show];
    
        while( !shit->_isCanceled ) {
            BOOL tmp = [run_loop runMode:NSDefaultRunLoopMode beforeDate:[NSDate date]];
        }
    
        return shit->_wasYes;
    }
    

    and finally the delegate method for handling the button click and stop the runloop-processing:

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
        _wasYes = (buttonIndex == 0);
        _isCanceled = YES;
    }
    

    This works but remember: you shouldn't do it this way :-D Pretty please don't argue about style and stuff, it's just a 5 minutes quick hack to proof it can be done! This should work without ARC (new -> autorelease) but if I'm wrong you know how to handle it ;)

    Disclaimer: I'm not responsible for any possible damage the use of this snippet could do to your application or devices. Thank you.

提交回复
热议问题