user559142 user559142 - 1 year ago 116
Objective-C Question

Make UIAlertView Button trigger function On Press

Currently I am using the following code to present a UIAlertView:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today's Entry Complete"
message:@"Press OK to submit your data!"
otherButtonTitles: nil];
[alert show];
[alert release];

How do I get it so that when 'OK" is pressed, it triggers a function, say

Answer Source


Important: UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is also deprecated.) To create and manage alerts in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert.

Please check this out tutorial

"deprecated" means???

Objectvie C

.h file

    @interface urViewController : UIViewController <UIAlertViewDelegate> {

.m file

// Create Alert and set the delegate to listen events
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today's Entry Complete"
                                                message:@"Press OK to submit your data!"
                                      otherButtonTitles:@"OK", nil];

// Set the tag to alert unique among the other alerts.
// So that you can find out later, which alert we are handling
alert.tag = 100;

[alert show];

//[alert release];

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    // Is this my Alert View?
    if (alertView.tag == 100) {

    // You need to compare 'buttonIndex' & 0 to other value(1,2,3) if u have more buttons.
    // Then u can check which button was pressed.
        if (buttonIndex == 0) {// 1st Other Button

            [self submitData];

        else if (buttonIndex == 1) {// 2nd Other Button


    else {
        // Other Alert View




The Swifty way is to use the new UIAlertController and closures:

    // Create the alert controller
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)

    // Create the actions
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
        UIAlertAction in
        NSLog("OK Pressed")
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")

    // Add the actions

    // Present the controller
    self.presentViewController(alertController, animated: true, completion: nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download