NSArray 的排序

NSArray *allkeys = [[NSArray alloc] initWithObjects:@"bca",@"abc",@"dca",@"cab",@"adc",@"acc",@"add",@"aaa",@"aab", nil];
    
    NSArray *sorteArray = [allkeys sortedArrayUsingComparator:^(id obj1, id obj2){
        
        if([obj1 compare:obj2] == NSOrderedDescending) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if([obj1 compare:obj2] == NSOrderedAscending) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    for(NSString *str in sorteArray){
        NSLog(@"%@",str);
    }
    [allkeys release];


NSMutableArray *array =  [[NSMutableArray alloc] init];

    [array addObject:[NSNumber numberWithInt:1]];

    [array addObject:[NSNumber numberWithInt:3]];

    [array addObject:[NSNumber numberWithInt:2]];

    

    NSArray *sorteArray = [array sortedArrayUsingComparator:^(id obj1, id obj2){

        if ([obj1 integerValue] > [obj2 integerValue]) {

            return (NSComparisonResult)NSOrderedDescending;

        }

        

        if ([obj1 integerValue] < [obj2 integerValue]) {

            return (NSComparisonResult)NSOrderedAscending;

        }

        

        return (NSComparisonResult)NSOrderedSame;

    }];

    

    NSLog(@"%@",sorteArray);            //从小到大

    

    

    NSArray *array2 = [array sortedArrayUsingComparator:^(id obj1, id obj2){

        if ([obj1 integerValue] > [obj2 integerValue]) {

            return (NSComparisonResult)NSOrderedAscending;

        }

        

        if ([obj1 integerValue] < [obj2 integerValue]) {

            return (NSComparisonResult)NSOrderedDescending;

        }

        

        return (NSComparisonResult)NSOrderedSame;

    }];

    

    NSLog(@"%@",array2);

    



    

    // ascending:  YES  为升序 NO  为降序

    NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];

    NSArray *arr1 = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];

    

    NSLog(@"%@",arr1);

你可能感兴趣的:(NSArray)