版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/M_15915899719/article/details/82775251
@protocol(协议)类似于JAVA的interface(接口),不同的是协议的方法可以不实现也可运行程序,协议中不可声明实例变量,只有声明方法且不能实现方法,遵守协议的类表示该类已经包含该协议的方法声明,只需要在类对应的.m文件中实现便可。
// 定义协议
@protocol ZMMainViewControllerDelegate <NSObject>
@required // 必选
- (void)showResultWithString:(NSString *)string;
@optional // 可选
- (void)showResultWithcontrl:(ZMMainViewController *)contrl;
@end
@interface ZMMainViewController : UIViewController
// 定义代理
@property (nonatomic, weak) id<ZMMainViewControllerDelegate> delegate;
在.m中
- (void)click {
// // 第一种方式进行传值
if (self.delegate && [self.delegate respondsToSelector:@selector(showResultWithString:)]) {
[self.delegate showResultWithString:self.textField.text];
}
}
这里要注意下,是self.deleagte去响应这个showResultWithString:方法,而不是self。
委托者.m文件中
- (void)click {
self.mainVc = [[ZMMainViewController alloc] init];
self.mainVc.delegate = self; // 设置代理,实现代理方法
[self presentViewController:self.mainVc animated:YES completion:nil];
}
// 通过代理传值
- (void)showResultWithString:(NSString *)string {
self.label.text = string;
}