通过使用Block实现从后往前传值
写协议或添加属性
@protocol SecondViewControllerDelegate<NSObject>
-(void)changeColor;
@end
@interface SecondViewController : UIViewController
@property(nonatomic,retain)id<SecondViewControllerDelegate>delegate;
@property(nonatomic,copy)void(^block)(NSMutableArray *);
@end
这是一个按钮的点击方法,当触发点击事件时实现方法
-(void)click:(UIButton *)button{
[self.navigationController popViewControllerAnimated:YES];
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"1",@"2",@"3", nil];
self.block(arr);
}
实现单击事件的方法用来调用block
-(void)click:(UIButton *)button{
void(^block)(NSMutableArray *) = ^(NSMutableArray *arr){
for (NSInteger i = 0; i < arr.count; i++) {
NSLog(@"%@",arr[i]);
}
};
SecondViewController *secVC = [[SecondViewController alloc]init];
secVC.block = block;
[self.navigationController pushViewController:secVC animated:YES];
[secVC release];
}
block传值练习
typedef void (^Block)(NSString *);
@interface SecondViewController : UIViewController
@property(nonatomic,copy)Block block;
@end
实现block传值的方法
@implementation SecondViewController
-(void)dealloc{
Block_copy(_block);
[super dealloc];
}
-(void)click:(UIButton *)button{
[self.navigationController popToRootViewControllerAnimated:YES];
self.block(@"跳涧虎 陈达");
}
被传值页面的实现方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
void(^block)(NSString *) = ^(NSString *str){
NSLog(@"%@",str);
[self.arr addObject:str];
UITableView *tableview = (UITableView *)[self.view viewWithTag:1000];
[tableview reloadData];
};
#pragma mark block作为属性的时候,为了防止block进入到栈区,栈区内存不需要我们进行管理,很可能出现block消失的情况,所以需要拷贝一份到堆区,这样能防止block在用的时候消失
SecondViewController *secVC = [[SecondViewController alloc]init];
secVC.block= block;
[self.navigationController pushViewController:secVC animated:YES];
[secVC release];
}