How do I sort an NSMutableArray with custom objects in it?

前端 未结 27 3360
予麋鹿
予麋鹿 2020-11-21 04:45

What I want to do seems pretty simple, but I can\'t find any answers on the web. I have an NSMutableArray of objects, and let\'s say they are \'Person\' objects

27条回答
  •  春和景丽
    2020-11-21 05:00

    Starting in iOS 4 you can also use blocks for sorting.

    For this particular example I'm assuming that the objects in your array have a 'position' method, which returns an NSInteger.

    NSArray *arrayToSort = where ever you get the array from... ;
    NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2) 
    {
        if ([obj1 position] > [obj2 position]) 
        { 
            return (NSComparisonResult)NSOrderedDescending;
        }
        if ([obj1 position] < [obj2 position]) 
        {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };
    NSArray *sorted = [arrayToSort sortedArrayUsingComparator:sortBlock];
    

    Note: the "sorted" array will be autoreleased.

提交回复
热议问题