标签:
定义一个block:
int (^blockname)(int, int);
blockname = ^(int a, int b){
return a>b ? a: b;
};
这个block等同于:
int (^blockname)(int, int) = ^(int a, int b){
return a>b?a:b;
};
使用:
NSInterge a = blockname(3, 4);
NSLog(@"a=%ld", a);
.block作为方法的参数
NSArray *nameArray = [NSArray arrayWithObjects:@"zhao", @"qian", @"sun", @"li", nil];
NSArray *arr = [nameArray sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@", arr);
NSMutableArray *numberArray = [NSMutableArray arrayWithObjects:@"2", @"1", @"10", @"015", nil];
NSArray *sortArray1 = [numberArray sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@", sortArray1);
NSArray *arr2 = [numberArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
//相邻两个元素(obj1, obj2)比较的规则
if ([obj1 intValue] > [obj2 intValue]) {
//相邻两个元素(obj1, obj2)的比较规则
//系统排序以满足NSOorderDescending的条件进行交换
//注: 快速判断拍好的数组, 以满足NSOrderAscending的条件为准
return NSOrderedAscending;
}else if ([obj1 intValue] == [obj2 intValue]){
return NSOrderedSame;
}else{
return NSOrderedDescending;
}
}];
标签:
原文地址:http://www.cnblogs.com/id-spring123/p/4523378.html