Wednesday, 13 May 2009

Running a UIAlertView modally

The funny thing about UIAlertView (and other iPhone modal interfaces), is that they don't actually run modally; in other words, you can't do something simple like this:
bool bResult = [myUIAlertView runModal];

Rather, the UIAlertView has a show method ... which shows the dialog, but which doesn't simply hang around and give you a result when done.

What you need to do in this situation, is create a delegate to handle the message generated when the UIAlertView button is pressed; and you must then provide you own modal processing loop!

Here is a simplified version of what you need to do. Spot the code loop that makes it all run modally!

// Create an instance of a custom UIAlertViewDelegate that we use to capture
// the events generated by the UIAlertView
MyUIAlertViewDelegate *lpDelegate = [[MyUIAlertViewDelegate alloc] init];

// Construct and "show" the UIAlertView (message, title, cancel, ok are all
// NSString values created earlier in your code...)
UIAlertView *lpAlertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:lpDelegate cancelButtonTitle:cancel otherButtonTitles:ok,nil];

[lpAlertView show];

// Run modally!
// By the time this loop terminates, our delegate will have been called and we can
// get the result from the delegate (i.e. what button was pressed...)
while ((!lpAlertView.hidden) && (lpAlertView.superview!=nil))
[[NSRunLoop currentRunLoop] limitDateForMode:NSDefaultRunLoopMode];

// Grab the result from our delegate (via a custom property)
int nResult = [lpDelegate result];

// Tidy up!
[lpAlertView release];
[lpDelegate release];

Hope that helps!


PhoC++ Framework said...


Where is the code of
MySleepMilli(10); function ?


Pete Cole said...


That is just a simple function that wraps-around nanosleep ...

I just did a quick look and found various example usages of nanosleep... very easy to use.

Hoping that helps!

Best wishes,


Reinaldo de O. Castro said...

Many thanks for your post! Helped me a lot!

Pete Cole said...

Happy to help! :)