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

前端 未结 27 3325
予麋鹿
予麋鹿 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:22

    iOS 4 blocks will save you :)

    featuresArray = [[unsortedFeaturesArray sortedArrayUsingComparator: ^(id a, id b)  
    {
        DMSeatFeature *first = ( DMSeatFeature* ) a;
        DMSeatFeature *second = ( DMSeatFeature* ) b;
    
        if ( first.quality == second.quality )
            return NSOrderedSame;
        else
        {
            if ( eSeatQualityGreen  == m_seatQuality || eSeatQualityYellowGreen == m_seatQuality || eSeatQualityDefault  == m_seatQuality )
            {
                if ( first.quality < second.quality )
                    return NSOrderedAscending;
                else
                    return NSOrderedDescending;
            }
            else // eSeatQualityRed || eSeatQualityYellow
            {
                if ( first.quality > second.quality )
                    return NSOrderedAscending;
                else
                    return NSOrderedDescending;
            } 
        }
    }] retain];
    

    http://sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html a bit of description

提交回复
热议问题