Search code examples
objective-ciosmacosnssortdescriptor

Blocks in NSSortDescriptors - Objective C


I have a switch statement which creates a relevant NSSortDescriptor. For some of the NSSortDescriptors I am using a block as a custom comparator (to compare CMTimes). The following code works fine but I would like to add some more NSSortDescriptors also comparing CMTimes. As the block is always the same is it possible to create a variable to hold the block so I don't need to keep copying and pasting messy code. I guess it should be possible but I can't seem to get it to work. I would greatly appreciate any help. Thank you!

NSSortDescriptor *sortDescriptor; 

switch (mode) {
    case 1:
        sortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"startTime" ascending: YES comparator:^(id first, id second){
                    CMTime time1 = [first CMTimeValue];
                    CMTime time2 = [second CMTimeValue];
                    if (CMTIME_COMPARE_INLINE(time1, <, time2)) 
                        return NSOrderedAscending;
                    else if (CMTIME_COMPARE_INLINE(time1, >, time2))
                        return NSOrderedDescending;
                    else
                        return NSOrderedSame;
        }];
        break;
    case 2:
        sortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"startTime" ascending: NO comparator:^(id first, id second){
                    CMTime time1 = [first CMTimeValue];
                    CMTime time2 = [second CMTimeValue];
                    if (CMTIME_COMPARE_INLINE(time1, <, time2)) 
                        return NSOrderedAscending;
                    else if (CMTIME_COMPARE_INLINE(time1, >, time2))
                        return NSOrderedDescending;
                    else
                        return NSOrderedSame;
        }];
        break;
    case 3:
        sortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"info" ascending: YES];
        break;
    case 4:       
        sortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"info" ascending: NO];
        break;
    default:
        break;
}

Solution

  • You can create a block variable so that you don't have to copy and paste the block code.

    NSComparator comparisonBlock = ^(id first,id second) {
        return NSOrderedAscending;
    };
    [NSSortDescriptor sortDescriptorWithKey: @"startTime" ascending: YES comparator:comparisonBlock];