今天看了一個pdf文檔,了解到了 協議的繼承,特別做了個小demo測試了一下,下面是代碼
OneDelegate.h
@protocol OneDelegate@required - (void)backStr:(NSString *)str; @end
@protocol TwoDelegate@optional - (void)backInt:(int)i; @end
#import "ViewController2.h" @interface ViewController : UIViewController@end
- (void)viewDidLoad { [super viewDidLoad]; UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(50, 50, 200, 100); button.backgroundColor = [UIColor yellowColor]; [button setTitle:@"into VC2" forState:UIControlStateNormal]; [button addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } - (void)push{ ViewController2 *vc = [[ViewController2 alloc]init]; vc.delegate = self; [self presentViewController:vc animated:YES completion:^{ }]; } //OneDelegate - (void)backStr:(NSString *)str{ NSLog(@"%@",str); } //TwoDelegate - (void)backInt:(int)i{ NSLog(@"%d",i); }
#import#import "two.h" @interface ViewController2 : UIViewController @property(nonatomic ,unsafe_unretained)id delegate; @end
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(50, 50, 200, 100); button.backgroundColor = [UIColor yellowColor]; [button addTarget:self action:@selector(backStrBtn) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button2.frame = CGRectMake(50, 200, 200, 100); button2.backgroundColor = [UIColor blueColor]; [button2 addTarget:self action:@selector(backIntBtn) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button2]; } - (void)backStrBtn{ if (self.delegate && [self.delegate respondsToSelector:@selector(backStr:)]) { [self.delegate backStr:@"這個是代理1的方法"]; } } - (void)backIntBtn{ if (self.delegate && [self.delegate respondsToSelector:@selector(backInt:)]) { [self.delegate backInt:2]; NSLog(@"這是繼承的方法"); } }