Search code examples
iosobjective-csortingnssortdescriptor

iOS how to sort NSMutableArray of custom object contained NSarray of NSNumber?


I have an array (NSMutableArray) which contains StudentScoreObj and the object have missions (NSArray).

Like:

missions = @[@34, @43, @54, @23, @54]; 

need to sort StudentScoreObj of array using first object of missions array.

My code:

@interface StudentScoreObj : NSObject

@property (nonatomic, copy) NSString *teamType;
@property (nonatomic, copy) NSString *teamNumber;
@property (nonatomic, copy) NSString *studentName;
@property (nonatomic, copy) NSString *isParticipated ;
@property (nonatomic, copy) NSString *totalScore;
@property (nonatomic, copy) NSString *avgScore;
@property (nonatomic, copy) NSArray *missions;

@end

Solution

  • You can use sorted​Array​Using​Comparator for that.

    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(StudentScoreObj *obj1,StudentScoreObj  *obj2) {
    
        NSNumber *obj1Score = @0, *obj2Score = @0;        
        if([[obj1 missions] firstObject]) {
            obj1Score = @([[[obj1 missions] firstObject] intValue]);
        }
    
        if([[obj2 missions] firstObject]) {
            obj2Score = @([[[obj2 missions] firstObject] intValue]);
        }
        return [obj1Score compare:obj2Score];
    }];