# OC基础学习12：代码块（Block）

2017-09-13 10:25:43来源:http://andyron.com/2017/oc-basic-12.html作者:欣欣向戎人点击

void (*my_func)(void);

*

（幂符号）变成代码块定义：

void (^my_block)(void);

int (^square_block)(int number) = ^(int number) {return (number * number);};
int result = square_block(5);
printf("Result = %d/n", result);

<returntype> (^blockname)(list of arguments) = ^(arguments){ body; };

void (^theBlock)(void) = ^{ printf("Hello Blocks!/n"); };

int value = 6;
int (^multiply_block)(int number) = ^(int number) { return (value * number);};
value = 8;
int result2 = multiply_block(7);
printf("Result2 = %d/n", result2);// 是6*7，不是8*7

NSArray *array = [NSArray arrayWithObjects:@"Amir", @"Mishal", @"Irrum", @"Adam", nil];
NSLog(@"Unsorted Array %@", array);
NSArray *sorteArray = [array sortedArrayUsingComparator:^(NSString *objet1, NSString *object2) {
return [objet1 compare:object2];
}];
NSLog(@"Sorted Array %@", sorteArray);

typedef double (^MKSampleMultiply2BlockRef)(double c, double d);
MKSampleMultiply2BlockRef multiply2 = ^(double c, double d) { return c * d; };
printf("%f, %f", multiply2(4, 5), multiply2(5,3));
typedef void (^MKSampleVoidBlockRef)(void);
typedef void (^MKSampleStringBlockRef)(NSString *);

Objective-C的实例变量

typedef double (^MKSampleMultiplyBlockRef)(void);
double a = 10, b = 20;
MKSampleMultiplyBlockRef multiply = ^(void){ return a * b; };
NSLog(@"%f", multiply());// 200.0
a = 20;
b = 50;
NSLog(@"%f", multiply());// 200.0

typedef double (^MKSampleMultiplyBlockRef)(void);
static double a = 10, b = 20;
MKSampleMultiplyBlockRef multiply = ^(void){ return a * b; };
NSLog(@"%f", multiply());// 200.0
a = 20; b = 50;
NSLog(@"%f", multiply());// 1000.0

typedef double (^MKSampleMultiply2BlockRef)(double c, double d);
MKSampleMultiply2BlockRef multiply2 = ^(double c, double d) { return c * d; };
printf("%f, %f", multiply2(4, 5), multiply2(5,3));

__block

double c = 3;
MKSampleMultiplyBlockRef multiply = ^(void) { c = 5; return c; };
//报错： Variable is not assignable (missing __block type specifier)

，就可以修改了

__block double c = 3;
MKSampleMultiplyBlockRef multiply = ^(void) { c = 5; return c; };