A页面:
A.h文件无内容.
A.m文件:
- (void)push
{
UILabel *label1 = (UILabel *)[self.view viewWithTag:1001];
TwoViewController *two = [[TwoViewController alloc]init];
[self.navigationController pushViewController:two animated:YES];
two.block = ^(NSString *str){ //block是TwoViewController类中的属性.
label1.text = str;
};
[two release];
[label1 release];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]autorelease];
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 100, 100, 30);
button.backgroundColor = [UIColor redColor];
[button addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(200, 200, 100, 30)];
label.backgroundColor = [UIColor greenColor];
label.tag = 1001;
[self.view addSubview:button];
[self.view addSubview:label];
[label release];
}
B页面:
B.h文件:
typedef void (^aBlock)(NSString *str);
@interface TwoViewController : UIViewController<UITextFieldDelegate>
@property (nonatomic, copy)aBlock block;
@end
B.m文件:
-(void)viewWillDisappear:(BOOL)animated
{
NSString *str = [NSString stringWithFormat:@"我是B页面的值"];
if (self.block) {
block(str);
}
}
当B页面返回A页面时会调用:two.block = ^(NSString *str){
label1.text = str;
};
这样"我是B页面的值"字符串就传到A页面了....
第一次创建TwoViewController对象时block里的值为空,固没有调用block函数..