iOS 反向传值
代理模式
1.委托需要进行的工作
1.1 定义协议与方法
1.2 声明委托变量
1.3 设置代理
1.4通过委托变量调用委托方法
2.代理需要做的工作
2.1遵循协议
2.2 实现委托方法
定义两个ViewController A(代理方), B(委托方)
在BViewController.h中:
//定义协议与方法
@protocol DeliverDetegate <NSObject>
- (void)setValue:(NSString *)string;
@end
@interface BViewController : UIViewController
//声明委托变量
@property (weak,nonatomic) id<DeliverDetegate>B_Delegate;
@end
在BViewController.m中:
@interface BViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *DeliverText;
@end
- (IBAction)DeliverAction:(id)sender {
//通过委托变量调用委托方法
//输入则显示输入的字符串,未输入显示“未填写”
if (![_DeliverText.text isEqualToString:@""]) {
NSLog(@"B向A发送数据%@",_DeliverText.text);
//判断代理中的方法是否被实现,避免未被实现代理的程序崩溃
if ([self.B_Delegate respondsToSelector:@selector(setValue:)])
{
[self.B_Delegate setValue:_DeliverText.text];
}
}
else
{
NSLog(@"B向A发送数据%@",@"未填写");
//判断代理中的方法是否被实现,避免未被实现代理的程序崩溃
if ([self.B_Delegate respondsToSelector:@selector(setValue:)])
{
[self.B_Delegate setValue:@"未填写"];
}
}
[self.navigationController popViewControllerAnimated:YES];
}
在AViewController.m中
#import "AViewController.h"
#import "BViewController.h"
@interface AViewController ()<DeliverDetegate>
@property (strong, nonatomic) IBOutlet UILabel *TextLabel;
@end
- (IBAction)ReceiveAction:(id)sender {
//遵循协议
BViewController*BVC = [[BViewController alloc]init];
BVC.B_Delegate = self;
[self.navigationController pushViewController:BVC animated:YES];
}
//实现委托方法,即实现的setValue方法
- (void)setValue:(NSString *)string
{
NSLog(@"A接收到B数据%@",string);
_TextLabel.text = string;
}
block
1.在BViewController中添加block
@interface NextViewController ()
@property (weak, nonatomic) IBOutlet UITextField *inputTF;
@end
//返回之前将要传递的数据放到block中返回
- (IBAction)clickButton:(id)sender
{
if (self.getSaySomethingBlock)
{
self.getSaySomethingBlock(_textField.text);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
2.在AViewController中使用block
- (IBAction)clickToBButton:(id)sender
{
UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
BViewController *bvc = [storyBoard instantiateViewControllerWithIdentifier:@"BViewController"];
bvc.getSaySomethingBlock = ^(NSString *somethingString){
self.label.text = somethingString;
};
[self presentViewController:bvc animated:YES completion:nil];
}
通知
使用NSNotificationCenter
//在BVC中发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"getString" object:@"aaaaaa"];
//在AVC 中接收通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNotification:) name:@"getString" object:nil];
//收到通知后调用的方法
- (void)getNotification:(NSNotification *)info
{
//发送的内容在info中
NSLog(@"%@", info);
}