
SecondViewController.h// 自定义Block属性
typedef void(^block) (NSString* secondString);
@interface SecondViewController : UIViewController
// 要传过去的字符串
@property (nonatomic, strong)NSString* string;
// 点击到第一界面
@property (nonatomic, strong)UIButton* nextButton;
// 定义block属性
@property (nonatomic, copy)block myBlock;
@end
"SecondViewController.m"** _myBlock(_string);#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor orangeColor];
self.title = @"有代码块的界面";
// 需要传过去的字符串
_string = [NSString stringWithFormat:@"被传过去的字符串"];
_nextButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[_nextButton setTitle:@"到达一级界面" forState:UIControlStateNormal];
_nextButton.frame = CGRectMake(0, 0, 200, 200);
[_nextButton addTarget:self action:@selector(pressButton) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_nextButton];
}
// 点击按钮事件的时候返回第一界面,并传值给代码块
- (void)pressButton {
_myBlock(_string);
[self dismissViewControllerAnimated:YES completion:nil];
}
ViewController.h@interface ViewController : UIViewController
@property (nonatomic ,strong) UILabel* label;
@property (nonatomic, strong) UIButton* lastButton;
@end
ViewController.m#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_label = [[UILabel alloc] init];
_label.font = [UIFont systemFontOfSize:21];
_label.frame = CGRectMake(100, 300, 200, 30);
[self.view addSubview:_label];
_lastButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[_lastButton setTitle:@"跳转到第二界面" forState:UIControlStateNormal];
[_lastButton addTarget:self action:@selector(pressButton) forControlEvents:UIControlEventTouchUpInside];
_lastButton.frame = CGRectMake(100, 400, 200, 30);
[self.view addSubview:_lastButton];
}
- (void)pressButton {
SecondViewController* View = [[SecondViewController alloc] init];
// 获取上一个界面的block 传给label
View.myBlock = ^(NSString* str) {
self.label.text = str;
};
[self presentViewController:View animated:YES completion:nil];
}
@end



我认为Block传值和协议传值的目的都是底下向外传,block是在二级界面自定义代码块,然后在二级界面的点击函数里传入需要的东西,一级界面在跳转的时候接受传值即可完成。
协议传值详解