//-------1、定义函数-----

//1、函数
int sum(int a,int b)
{
return a+b;
}
//------------------2、声明--------- //2、声明函数指针【将sum换成*p就能够了】
int (*p)(int a,int b); //(1)声明block【将sum换成^myBlock就能够了】
int (^myBlock)(int a,int b); //举一反三
void (^myBlock2)(void);
- (void)viewDidLoad
{
[super viewDidLoad]; //---------------------3、赋值【不同之处】------------------
// 3、给函数指针赋值
p = sum;
//(2)将函数赋值给myBlock【^后面加參数列表,以及代码块内容,并以“;”结束】
myBlock = ^(int a,int b)
{
return a+b;
}; //---------------------4、调用------------------
//4、调用
int result = p(3,6);
NSLog(@"%d",result);
//(3)调用
int resultBlock = myBlock(3,6);
NSLog(@"%d",resultBlock); myBlock2 = ^(void)
{
NSLog(@"myBlock2运行了");
}; myBlock2(); //---------------------二、文件之间传值------------------
//block的调用
Person *person = [[Person alloc]init];
//1-2实现block
// ^int(int a, int b) {
// return a+b;
// }
//把person的10和20传到本文件里
//局部变量到block中是常量。如需改变值则须要在声明前面加 __block
__block int number = 10; int resultPs = [person testMethod:^int(int a, int b) {
number = 20;
return a+b+number;
}];
//typedef 方式创建
int resultPs2 = [person testMethod2:^int(int a, int b) {
return a+b;
}];
NSLog(@"resultPs:%d resultPs2:%d",resultPs,resultPs2); } @end

Person.h

#import <Foundation/Foundation.h>
//这里的PersonBlock是类型名字,能够理解为int
typedef int(^PersonBlock) (int a,int b);
@interface Person : NSObject //1-1在參数中声明【int(^)(int a, int b】
- (int)testMethod:( int(^)(int a, int b) )block;
//这里不须要加星号
- (int)testMethod2:(PersonBlock)block;
@end

Person.m

#import "Person.h"

@implementation Person
//1-3调用block
- (int)testMethod:( int(^)(int a, int b) )block
{
return block(10,20);
} - (int)testMethod2:(PersonBlock)block
{
return block(1,2);
}
@end

05-11 22:56