block排序方法

来源:互联网 发布:数据透视表在哪 编辑:程序博客网 时间:2024/05/23 22:15
<span style="font-family:Tahoma;font-size:14px;"><pre name="code" class="objc">namesArray = [namesArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {                        if ([obj1 compare:obj2] == NSOrderedAscending) { // 原本升序   NSOrderedDescending 代表降序                return 1l;            }            return 0;        }];                NSLog(@"%@", namesArray);                        // 可变数组排序,使用的排序方法,没有返回值        NSMutableArray *numbersArray = [NSMutableArray arrayWithObjects:@"123", @"345", @"234", @"56", @"2356", nil];                [numbersArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {                        if ([obj1 intValue] < [obj2 intValue]) {                return 1l;            }            return 0;        }];                NSLog(@"%@", numbersArray);</span>

//系统排序方法 


<span style="font-family:Tahoma;font-size:14px;">typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending}; - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr NS_AVAILABLE(10_6, 4_0); - (void)sortUsingComparator:(NSComparator)cmptr NS_AVAILABLE(10_6, 4_0);</span>

<span style="font-family:Tahoma;font-size:14px;">// 数组怎么用block排序                NSArray *namesArray = @[@"daozhang", @"baoge", @"fage", @"yangyang", @"gege", @"qiqi"];                NSComparisonResult (^sortBlock) (id, id) = ^(id obj1, id obj2) {            return [obj1 compare:obj2];        };                // 使用block进行排序        namesArray = [namesArray sortedArrayUsingComparator:sortBlock];        NSLog(@"%@", namesArray);</span>

对类的对象进行排序


<span style="font-family:Tahoma;font-size:14px;">Student *stu1 = [Student StudentWithnum:1001 name:@"Yadong" age:23 score:99.8];        Student *stu2 = [Student StudentWithnum:1002 name:@"Yadong" age:26 score:98.8];        Student *stu3 = [Student StudentWithnum:1003 name:@"Yadong" age:43 score:95.8];        Student *stu4 = [Student StudentWithnum:1004 name:@"Yadong" age:83 score:97.8];        Student *stu5 = [Student StudentWithnum:1005 name:@"Yadong" age:13 score:79.8];                NSMutableArray *studentArray = [NSMutableArray arrayWithObjects:stu1, stu2, stu3, stu4, stu5, nil];                // 按照年龄,从小到大排序                [studentArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {                        Student *s1 = obj1;            Student *s2 = obj2;                        if (s1.age > s2.age) {                return 1l;            }            //            if ([obj1 age] < [obj2 age]) {//                return 1l;//            }            return 0;        }];                        NSLog(@"%@", studentArray);</span>

0 0
原创粉丝点击