I need to call a UIAlertView to be displayed from a C++ file. Depending on the button pressed, I need to return a bool to the C++ class itself (that bool in turn gets returned and is used elsewhere). I would like some advice on how to return the result to the C++ class. I have presumed that we can’t set the C++ class as the delegate for the UIAlertView, so I need to somehow pass back which button is pressed to the C++ class.
This is the sample function call from C++ (it’s a C++ class, but compiled as Objective-C:
bool CPlatform::WarningMessage(const wchar_t* message)
{
// Some functions to convert message to an NSString* wNSString
MessagePopUp *message = [[MessagePopUp alloc] init];
[message showPopUpWithMessage:wNSString];
// This function should return true if OK is pressed, or False if Cancel is pressed.
}
Then, I have a simple class to display the alert
@interface MessagePopUp : NSObject <UIAlertViewDelegate> {
BOOL OKPressed;
}
- (void) showPopUpWithMessage:(NSString*)message;
@end
@implementation MessagePopUp
- (void) showPopUpWithMessage:(NSString*)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:message delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
// the user clicked one of the OK/Cancel buttons
if (buttonIndex == 0)
{
NSLog(@"ok");
OKPressed = true;
}
else
{
NSLog(@"cancel");
OKPressed = false;
}
}
@end
Can you recommend a way that I can return the result / OKPressed to the C++ function?
Thanks
You can’t do this easily as thinking about the code flow will tell you.
The problem is the run loop and that UIAlertView is non blocking to display the alertView (i.e. after calling
[alert show]) you need to return control to iOS which means that your C++ functionbool CPlatform::WarningMessage(const wchar_t* message)must return before you know which button has been pressed.You could try and build a blocking UIAlertView but it’s not a good idea even though this type of thing is possible.
A better idea would be to go with the flow and define a callback in your C++
CPlatformclass which accepts theOKPressedbool you have in yourclickedButtonAtIndexdelegate method.