标签:
int (^myBlock)(int,int) = ^(int num1, int num2) { return num1 + num2; }; NSLog(@"%d",myBlock(5,4));
// 1.定义无返回值、无参的Block void (^block1)() = ^() { NSLog(@"无返回无参的Block"); }; block1();
// 2.定义无返回值、有参数的Block void (^block2)(int) = ^(int a) { NSLog(@"%d",a); }; block2(2);
// 3.定义返回值为OC对象的Block NSString *(^block3)(NSString *) = ^(NSString *string) { string = [NSString stringWithFormat:@"%@_%@",string,string]; return string; }; NSLog(@"%@",block3(@"我是字符串"));
int x = 5; int (^block4)(int) = ^(int y) { int z = x + y; return z; }; NSLog(@"%d,%d",x +=5,block4(5));
打印的值是10,10;
__block int x = 5; int (^block4)(int) = ^(int y) { int z = x + y; return z; }; NSLog(@"%d,%d",x +=5,block4(5));
打印的值是10,15;
// 第一步定义, Block作为property属性 /* void: Block的返回值为空,即无返回值; colorBlock: Block的作为对象属性时的属性名; (UIColor *color): Block的参数是UIColor实例对象 */ @property (nonatomic, copy) void(^colorBlock)(UIColor *color);
// 随机生成的颜色 UIColor *color = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1]; // 第二步 给Block传入参数color if (self.colorBlock) { self.colorBlock(color); } [self dismissViewControllerAnimated:YES completion:nil];
FirstViewController *fvc = [[FirstViewController alloc] init]; // 执行Block代码块 fvc.colorBlock = ^(UIColor *color) { self.view.backgroundColor = color; };
标签:
原文地址:http://www.cnblogs.com/laoNanHai/p/5537037.html