新QQ交流群:418536818,之前的群已满
代码块传值相对简单,所要写的代码少。
首先定义两个类,FirstViewController和SecondViewController
在AppDelegate.m文件中
self.window.rootViewController = [[UINavigationControlleralloc]initWithRootViewController:fV];
在第二个页面h文件中
#import <UIKit/UIKit.h>
@class SecondViewController;
typedef void(^myBlock)(SecondViewController * con );
@interface SecondViewController : UIViewController
@property(nonatomic,strong)myBlock block;//或者@property (nonatomic, copy) void(^requestSuccessHandler)(NSInteger requestType);
@end
注意typedef block -c block typedef定义一个代码块
在.m文件中
-(void)viewWillAppear:(BOOL)animated{
if (self.block) {
self.block(self);//自动调用Setting方法执行代码块
}
}
在第一个页面中
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view.
//定义一个按钮
UIButton* button = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 100, 100, 100);
button.backgroundColor = [UIColorredColor];
[button addTarget:selfaction:@selector(doButton)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:button];
}
-(void)doButton{
SecondViewController * seV =[[SecondViewControlleralloc]init];
UIView *view = [[UIViewalloc]initWithFrame:CGRectMake(100,100,100,100)];
[view setBackgroundColor:[UIColorredColor]];
[seV setBlock:^(SecondViewController * con ){
//所传的代码
[con.view addSubview:view];
}];
[self.navigationControllerpushViewController:seVanimated:YES];
}
另外代码块的内外传值要用__block
__block SecondViewController *blockSelf =self;//少用,容易引起内存泄露
__block NSString * str ;
//-------------------------------------------------------------//另一种方式
@property (nonatomic, copy) void(^returnSuccess)(BOOL isNo);
if (self.returnSuccess) {
self.returnSuccess(status);
}
[socketupzip setReturnSuccess:^(BOOL yesNo) {
if (yesNo) {
NSLog(@"socket上传成功");
}else{
NSLog(@"socket上传失败");
}
}];