Complete Guide to Creating Simple UIAlertView in iOS

Dec 04, 2025 · Programming · 9 views · 7.8

Keywords: iOS | UIAlertView | Objective-C

Abstract: This article provides a comprehensive guide to creating simple UIAlertView in iOS development, including Objective-C code examples, delegate protocol implementation, and the UIAlertController alternative for iOS 8+. Starting from basic implementation, it progressively explores button event handling, memory management considerations, and version compatibility strategies, offering thorough technical reference for developers.

Basic Implementation of UIAlertView

In iOS development, UIAlertView serves as a core component for displaying warning or confirmation dialogs to users. To create a simple UIAlertView, developers need to understand its initialization parameters and display mechanism. Below is a complete Objective-C implementation example:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ROFL" 
                                                message:@"Dee dee doo doo." 
                                                delegate:self 
                                                cancelButtonTitle:@"OK" 
                                                otherButtonTitles:nil];
[alert show];

This code creates an alert view containing a title, message, and an "OK" button. The delegate parameter specifies the delegate object handling button click events, cancelButtonTitle defines the cancel button's title, and otherButtonTitles allows adding additional buttons (set to nil in this example indicating no extra buttons).

Delegate Protocol and Event Handling

To respond to user button clicks, the UIAlertViewDelegate protocol must be implemented. First, conform to this protocol in the view controller's interface declaration:

@interface YourViewController : UIViewController <UIAlertViewDelegate>

Then, implement the alertView:didDismissWithButtonIndex: method to handle button click events:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // Logic for handling "OK" button click
    }
}

In this method, the buttonIndex parameter represents the index of the clicked button, where 0 corresponds to the cancel button (i.e., the "OK" button). Developers can add custom business logic here.

Memory Management Considerations

In non-ARC (Automatic Reference Counting) environments, manual memory management for UIAlertView is required. After creating the alert view, the release method should be called at the appropriate time:

// Memory management in non-ARC environments
[alert release];

In ARC environments, the system automatically handles memory release, eliminating the need for explicit release calls. This distinction is crucial for maintaining code compatibility and stability.

Modern Alternative with UIAlertController

Starting from iOS 8, Apple introduced UIAlertController as a unified replacement for both UIAlertView and UIActionSheet. Below is the Objective-C code for creating a simple alert controller in iOS 8+:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title"
                                                                         message:@"Message"
                                                                  preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
                                                   style:UIAlertActionStyleDefault
                                                 handler:nil];
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];

The corresponding Swift implementation is as follows:

let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
let actionOk = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(actionOk)
self.present(alertController, animated: true, completion: nil)

UIAlertController adopts a more modern API design, managing button behaviors through UIAlertAction objects and using closures (in Swift) or blocks (in Objective-C) to handle button click events, offering more flexible interaction patterns.

Version Compatibility Strategy

Given that UIAlertView is deprecated in iOS 8, while UIAlertController is only available for iOS 8 and above, developers need to implement version detection to ensure application compatibility across different systems. Below is an Objective-C example of compatibility handling:

NSString *alertTitle = @"Title";
NSString *alertMessage = @"Message";
NSString *alertOkButtonText = @"Ok";

if (@available(iOS 8, *)) {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
                                                                             message:alertMessage
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:alertOkButtonText
                                                       style:UIAlertActionStyleDefault
                                                     handler:nil];
    [alertController addAction:actionOk];
    [self presentViewController:alertController animated:YES completion:nil];
} else {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
                                                        message:alertMessage
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:alertOkButtonText, nil];
    [alertView show];
}

The corresponding Swift implementation:

let alertTitle = "Title"
let alertMessage = "Message"
let alertOkButtonText = "Ok"

if #available(iOS 8, *) {
    let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
    let actionOk = UIAlertAction(title: alertOkButtonText, style: .default, handler: nil)
    alertController.addAction(actionOk)
    self.present(alertController, animated: true, completion: nil)
} else {
    let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText)
    alertView.show()
}

This conditional compilation strategy ensures that the application uses UIAlertView on older iOS versions while employing the more modern UIAlertController on newer versions, thereby providing a consistent user experience.

Core Concept Summary

Creating simple alert dialogs involves multiple key concepts: initialization parameter configuration, delegate protocol implementation, memory management rules, and version compatibility handling. Developers should prioritize using UIAlertController for new development while maintaining UIAlertView as a fallback for supporting older systems. By understanding the design philosophy and API evolution of these components, developers can write more robust and maintainable iOS application interface code.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.