一、函数指针的作用
void (*p)(); //声明函数指针 声明的函数指针与指向的函数名返回值与参数列表都要匹配
p = fun; //函数指针指向函数名
p(); //函数指针调用函数
二、block的定义与调用方式
//无参数无返回值的block
void (^block)(); //block的声明
block = ^{ //block指向空的函数名 调用步骤: 1
NSLog(@"block 调用"); //^内部类似函数体 3
};
block(); //调用block块 2
//带参数无返回值的block
void (^block1)(int count); //带参数的block声明
block1 = ^(int count){ //block1指向^(int count){}
NSLog(@"block1 调用,count=%d",count);
};
block1(10);
//带参数有返回值的block
int (^block2)(int count); //声明
block2 = ^(int count){
NSLog(@"block2调用,count=%d",count);
return count+20; //带返回值
};
int count = block2(15); //带参数的block调用
NSLog(@"count=%d",count);
三、typedef block
//不带参的block类型
typedef void (^blockType)();
//将“void (^)()”重命名为 blockType
//带参的block类型
typedef void (^blockType1)(NSString *);
typedef NSString *(^blockType2)(NSString *value1,NSString *value2);
typedef int my _int_32; //注意与上面的区别
//block 作为参数传递
-(void)sleep:(blockType1)block;
四、block 修饰符
__block int count = 10;
//加入__block修饰符后,在block体中可读写count变量,否则不会改变原值
void (^block)() = ^{
count += 10;
//count变量不加__block修饰符,block块内部为可读权限
NSLog(@"count=%d",count);
};
block();
五、block 内联
- (void)doSomeThing:(void (^)())block;
- (void)doSomeThing:(void (^)(NSString obj, NSUInteger index))block;
- (void)doSomeThing:(NSString (^)(NSString *obj, NSUInteger index))block;