今天看了一个pdf文档,了解到了 协议的继承,特别做了个小demo测试了一下,下面是代码
OneDelegate.h
@protocol OneDelegate <NSObject>
@required
- (void)backStr:(NSString *)str;
@end
@protocol TwoDelegate <OneDelegate>
@optional
- (void)backInt:(int)i;
@end
ViewController.h
#import "ViewController2.h"
@interface ViewController : UIViewController <TwoDelegate>
@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);
}
ViewController2.h
#import <UIKit/UIKit.h>
#import "two.h"
@interface ViewController2 : UIViewController
@property(nonatomic ,unsafe_unretained)id delegate;
@end
ViewController2.m
- (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(@"这是继承的方法");
}
}