为什么我不需要在标题中声明UIAlertViewDelegate? [英] Why do I not need to declare UIAlertViewDelegate in the header?
问题描述
//。h
#import< UIKit / UIKit.h>
// @ interface ViewController:UIViewController< UIAlertViewDelegate>
@interface ViewController:UIViewController
- (IBAction)showMessage:(id)sender;
@end
//.m
#importViewController.h
@implementation ViewController
- (IBAction)showMessage:(id)sender {
UIAlertView * message = [[UIAlertView alloc] initWithTitle:@Hello World!
消息:@消息。
delegate:self
cancelButtonTitle:@取消
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(@1已选中);
}
}
@end
您的标题中的< UIAlertViewDelegate>
只是指示您打算在类中实现委托方法的编译器。如果不执行标记为@required的委托方法,则会收到警告,但是由于大多数委托方法通常都是@optional,代码将被编译并运行正常。这并不意味着您不应该在标题中添加代理。
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.
这篇关于为什么我不需要在标题中声明UIAlertViewDelegate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!