How to use UIAlertView?

This Tutorial deals with how to use UIAlertView in your application…

Let us suppose our viewController class is myViewController and we want an alert on the press of a button

Drag a button from library to view in myViewController.xib

Now come to myViewController.h

Add the following highlighted lines of code

Now in myViewController.m

Add the implementation of “showAlert”

-(IBAction)showAlert
{
	UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Alert" message:@"Alert user" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"button1",@"button2",nil];
	[alert show];
	[alert release];
}

Also add the following delegate method

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	NSLog(@"Pressed button %d",buttonIndex);
}

The above delegate method will get called everytime you press some button on UIAlertView and will tell the index number of the button pressed

In myViewController.xib make the connections as shown

Save and run application. Output is shown below

Now see how delegation method works. Suppose buttons are pressed in order   button1->Show Alert->button2->Show Alert->OK

then see the output on console