1. Block作为参数,传递执行语句
void Work(void (^dothings)()){
NSLog(@"eating...");
dothings();
NSLog(@"go home...");
}
void WorkDay(int workday){
void (^workThing)();
switch (workday) {
case 1:
workThing = ^(){
NSLog(@"报到。。。");
};
break;
case 2:
workThing = ^(){
NSLog(@"分析工作内容。。。");
};
break;
case 3:
workThing= ^(){
NSLog(@"敲代码。。。");
};
break;
case 4:
workThing = ^(){
NSLog(@"晋升产品经理。。。");
};
break;
case 5:
workThing = ^(){
NSLog(@"have a happy life。。。");
};
break;
default:
break;
}
Work(workThing);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
for (int i = 1; i<=5;i++)
WorkDay(i);
}
return 0;
}
2. Block作为返回值
typedef void(^NewType1) ();
typedef int(^NewType2) (int a,int b);
NewType1 testType1(){
NewType1 n1 = ^{
NSLog(@"this is newtype1...");
};
return n1;
}
NewType2 testType2(){
// NewType2 n2;
// n2 = ^(int a,int b){
// return a + b;
// };
// return n2;
return ^(int a,int b){
return a + b;
};
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NewType1 n1 = testType1();
n1();
NewType2 n2 = testType2();
int a = n2(10,201);
NSLog(@"%d",a);
}
return 0;
}
3. Block 作为类属性
BlockAsPara.h
#import <Foundation/Foundation.h>
typedef void(^BlockType) ();
typedef int(^IntBlock) (int a,int b);
@interface BlockAsPara : NSObject
- (void)test:(BlockType) block;
//- (void)test:(void(^)())block;
- (void)addTest:(int(^)(int ,int))block andInt:(int)a andInt:(int)b;
- (void)multiTest:(int(^)(int ,int )) block andInt:(int)a andInt:(int)b;
@end
BlockAsPara.m
#import "BlockAsPara.h"
@implementation BlockAsPara
//- (void)test:(void (^)())block{
// if (block != nil) {
// block();
// }
//}
- (void)test:(BlockType)block{
if (block != nil) {
block();
}
}
- (void)addTest:(int (^)(int, int))block andInt:(int)a andInt:(int)b{
if (block != nil) {
block(a,b);
}
}
- (void)multiTest:(int (^)(int , int ))block andInt:(int)a andInt:(int)b{
if (block != nil) {
NSLog(@"%d * %d = %d",a, b, block(a,b));
}
}
@end
mian.m
void (^b3)() = ^(){
NSLog(@"bbb");
};
b3();
int (^b4)(int a,int b);
b4 = ^(int a,int b){
return a * b;
};
[bp multiTest:b4 andInt:2 andInt:3];