//int (^)(int x, int y) block变量的类型
//block -- block变量的名字
//^(int x, int y)
//{
// return x + y;
//} ---- block变量的初值,block用来存储函数,所以给block变量赋值时赋的是整个函数的实现.
int (^block)(int x, int y) = ^(int x, int y)
{
return x + y;
};
//当把函数的实现赋给block变量之后,block变量就可以当做函数名使用.
int sum = block(4, 7);
NSLog(@"sum = %d", sum);
//求两个数的最大值
int (^blockMax)(int x, int y) = ^(int x, int y) {
return x > y ? x : y;
};
int max = blockMax(6, 8);
NSLog(@"max = %d", max);
//求两个数最小值
typedef int (^blockMin)(int, int);
blockMin min = ^(int x, int y) {
return x > y ? y : x;
};
int min1 = min(5, 9);
NSLog(@"min = %d", min1);
//voic (^)() 变量类型
typedef void (^Print)();
Print sayHi = ^() {
NSLog(@"Hello");
};
sayHi();
__block int a = 10;
//当在block内部使用block外部定义的局部变量时,如果 变量没有被__block修饰,则在block内部是readonly(只读的),不能对它修改,如果想修改,变量前必须要有_block修饰.
//__block的作用告诉编译器,编译时在block内部不要把外部变量当做常量使用,还是当做变量使用
//如果再block中访问全局变量,不需要__block修饰.
int (^max1)(int x, int y) = ^(int x, int y) {
//variable is not assignable
//变量不可更改
a = 200;
b = 30;
return x * 20;
};
<pre name="code" class="cpp">
NSArray *arr = [[NSArray alloc] initWithObjects:@"aa", @"bb", @"cc", @"dd", @"ff", nil];
//1.对数组进行升序排序
//sortedArrayUsingSelector:排序方式的使用场景:适用于升序排序以及自定义的类排序
NSArray *sortArrAscenging = [arr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@", sortArrAscenging);
//2.对数组进行降序排序
//block方式的排序方法,使用场景:适用于当数组中的对象类型是系统类型时,并且要降序排序时.
NSArray *sortArrDescending = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//对block匿名函数实现,比较方法
//1.将id类型转为NSSting *
NSString *str1 = (NSString *)obj1;
NSString *str2 = (NSString *)obj2;
//2.字符串比较
return -[str1 compare:str2];
}];
NSLog(@"%@", sortArrDescending);