Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I not need to declare UIAlertViewDelegate in the header?

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
like image 691
SimonRH Avatar asked Dec 01 '22 23:12

SimonRH


1 Answers

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.

like image 154
DrummerB Avatar answered Dec 05 '22 08:12

DrummerB