Block传值
typedef void(^DemoBlock)(); typedef void(^INTBlock)(int a, int b); @property(nonatomic,assign)DemoBlock demoBlock; @property(nonatomic,assign)INTBlock initBlock; -(void)creatdemoBlock:(DemoBlock)demoBlock InitBlock:(INTBlock)initBlock{ demoBlock(); initBlock(10,20); } [self creatdemoBlock:^{ NSLog(@"hehehe"); }InitBlock:^(int a, int b) { NSLog(@"%d",a+b);//30 }];
int (^Myblock)(int,int) = ^(int a , int b){ return a+b; }; int(^Myblock2)() = ^(){ return 10; }; int (^Myblock3)() =^{ return 20; }; NSLog(@"%d",Myblock(10,20));//30 NSLog(@"%d",Myblock2());//10 NSLog(@"%d",Myblock3());//20
self.memberVariable = 20; // NSInteger outsideVariable = 20;//如果不添加_block则block会捕获该值 //添加了_block则会跳过获取后面的值,如果没有则显示此值。 __block NSInteger outsideVariable = 10; NSMutableArray * outsideArray = [[NSMutableArray alloc] init]; void (^blockObject)(void) = ^(void){ NSInteger insideVariable = 20;//不会变 NSLog(@" > member variable = %ld", (long)self.memberVariable);//20 NSLog(@" > outside variable = %ld", (long)outsideVariable);//有_block:30?20 NSLog(@" > inside variable = %ld", (long)insideVariable);//20 [outsideArray addObject:@"AddedInsideBlock"]; }; outsideVariable = 30; self.memberVariable = 30; blockObject(); NSLog(@" > %lu items in outsideArray", (unsigned long)[outsideArray count]);
1、在需要回调的B界面:.h
//1、定义一个Block 返回字符串 typedef void(^ReturnTextStr)(NSString*str); //2、声明一个Block @property(nonatomic,strong)ReturnTextStr returnStrBlock; //3、声明一个Block方法 -(void)returenText:(ReturnTextStr)block;
2、在需要回调B界面: .m
//4、 -(void)returenText:(ReturnTextStr)block{ _returnStrBlock = block; } //5、 - (IBAction)back:(id)sender { [self dismissViewControllerAnimated:YES completion:^{ if (_returnStrBlock != nil ) { _returnStrBlock(self.blockTEXT.text); } }]; }
3、接收返回值得A界面
@interface ViewController (){ BVCViewController*bvc; } - (IBAction)gotoVC:(id)sender { bvc = [[CViewController alloc]initWithNibName:@"CViewController" bundle:nil]; // 5 [bvc returenText:^(NSString *str) { self.A.text = str; }]; [self presentViewController:bvc animated:YES completion:nil]; }