简体   繁体   中英

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

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];
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM