// 创建一个block
// 1.返回值
// 2.使用‘^’标记一个Block,并写出Block变量
// 3.确定Block参数列表,参数名可以省略
// 4.‘^’
// 5.参数列表
// 6.主题部分,‘{};’
// 7.在‘{}’内部写具体实现
int (^myBlock)(int, int) = ^(int a, int b){
return a + b;
};
int (^myBlock1)(int, int) = ^(int c, int d){
return c + d;
};
NSInteger (^Ming)(NSString *) = ^(NSString *p){
return [p integerValue];
};
//Block与变量
//在Block内部:
//1.全局变量既可以访问,也可以修改
//2.局部变量只可以访问,不可以修改;如果想要修改,需要使用__block修改局部变量
__block int count = 5;
int (^sum)(int) = ^(int a){
count = 20; // 修改局部变量
return a * count;
};
NSLog(@"%d",sum(10));
//使用Block对数组进行排序
NSArray *arr = [NSArrayarrayWithObjects:@"asf 60",@"ab 54",@"78",nil];
NSComparator sortBlock = ^(id obj1, id obj2){
return [obj1 compare:obj2];
};
arr = [arr sortedArrayUsingComparator:sortBlock];
NSLog(@"%@",arr); //字符串比较排序
[arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];
}];
//根据数值排序
NSArray *arr1 = [NSArrayarrayWithObjects:@"456",@"15",@"97",@"1123", nil];
NSComparator paixu = ^(id obj1, id obj2){
return [obj1 compare:obj2];
};
arr1 = [arr1 sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSInteger obj1Int = [obj1 integerValue];
NSInteger obj2Int = [obj2 integerValue];
if (obj1Int > obj2Int) {
returnNSOrderedDescending;
}else if(obj1Int < obj2Int){
return NSOrderedAscending;
}else{
return NSOrderedSame;
}
}];
NSLog(@"%@",arr1);
//创建5个学生对象
Student *stu1 = [[Studentalloc]initWithName:@"zhang"withAge:12];
Student *stu2 = [[Studentalloc]initWithName:@"li"withAge:21];
Student *stu3 = [[Studentalloc]initWithName:@"sun"withAge:18];
Student *stu4 = [[Studentalloc]initWithName:@"wang"withAge:32];
NSMutableArray *stu = [NSMutableArrayarray];
[stu addObject:stu1];
[stu addObject:stu2];
[stu addObject:stu3];
[stu addObject:stu4];
[stu sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
Student *stu1 = (Student *)obj1;
Student *stu2 = (Student *)obj2;
if ([stu1 getage] > [stu2 getage]) {
return NSOrderedDescending;
}if ([stu1 getage] < [stu2 getage]) {
return NSOrderedAscending;
}else{
return NSOrderedSame;
}
}];
for (Student *student in stu) {
NSLog(@"%@", student);
}
NSLog(@" ");
[stu sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
Student *stu1 = (Student *)obj1;
Student *stu2 = (Student *)obj2;
return [[stu1 getname]compare:[stu2 getname]];
}];
for (Student *str in stu) {
NSLog(@"%@", str);
}
//字面量的使用
NSString *p = @"abc";
NSArray *arry =@[@"A", @"B", @"C"];
NSArray *a = a[2];
NSDictionary *dict = @{@"kkk": @"ooo",@"kk2": @"ooo"};
NSLog(@"%@",dict[@"kkk"]); //dict[@"xxx"] 提取“键”对应的值
@{@"asd": @"789"}; //设置键、值
block 数值排序 字面量的使用,布布扣,bubuko.com
原文:http://www.cnblogs.com/mingtiannihao/p/3721042.html