I thought I had finally managed to understand the concept of a delegate until the following occurred: I changed my header file to remove the reference to the delegate and the Alert still worked. The only difference is that I lose code hinting.
//.h
#import <UIKit/UIKit.h>
//@interface ViewController : UIViewController <UIAlertViewDelegate>
@interface ViewController : UIViewController
- (IBAction)showMessage:(id)sender;
@end
//.m
#import "ViewController.h"
@implementation ViewController
- (IBAction)showMessage:(id)sender {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"
message:@"Message."
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Button 1", @"Button 2", nil];
[message show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:@"Button 1"])
{
NSLog(@"Button 1 was selected.");
}
}
@end
The <UIAlertViewDelegate>
in your header is just an indication to the compiler that you intend to implement the delegate methods in your class. You will get warnings if you don't implement delegate methods that are marked as @required, but since most of the delegate methods are usually @optional your code will compile and run fine. That doesn't mean that you shouldn't add the delegates in your header though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With