Two NSMutableArrays sorted according objects of first one

时间:2022-09-06 21:25:09

I have two NSMutableArrays with NSString and NSNumber objects, more specific:

我有两个NSMutableArrays与NSString和NSNumber对象,更具体:

NSMutableArray * points; // NSNumber objects
NSMutableArray * players; //NSString objects

and i need to sort both of them according the objects of points. I try this Order two NSMutableArrays based on one but didn't help because of NSArray. I need to do this in NSMutableArrays. I sort points using this

我需要根据点的对象对它们进行排序。我尝试这个Order两个NSMutableArrays基于一个但由于NSArray没有帮助。我需要在NSMutableArrays中执行此操作。我用这个来分类

NSSortDescriptor *highestToLowest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
[points sortUsingDescriptors:[NSArray arrayWithObject:highestToLowest]];

1 个解决方案

#1


3  

I think you should introduce a Player Class

我想你应该介绍一个Player类

@interface Player : NSObject
@property(strong) NSString *name;
@property(strong) NSNumber *points;
@end

Instead of keeping the informations in seperated arrays, you would now have a Player object for each player and keep the point inside. Now put all the players in an array, that you can sort easily.

现在,您不必将信息保存在单独的数组中,而是为每个玩家设置一个Player对象并将其保持在内部。现在把所有玩家放在一个数组中,你可以轻松排序。

[players sortUsingComparator: ^(Player *p1, Player *p2){
    if (p1.points < p2.points)
        return NSOrderedAscending;   
    else if(p1.points > p2.points)
        return NSOrderedDescending 
    return NSOrderedSame;
}];

#1


3  

I think you should introduce a Player Class

我想你应该介绍一个Player类

@interface Player : NSObject
@property(strong) NSString *name;
@property(strong) NSNumber *points;
@end

Instead of keeping the informations in seperated arrays, you would now have a Player object for each player and keep the point inside. Now put all the players in an array, that you can sort easily.

现在,您不必将信息保存在单独的数组中,而是为每个玩家设置一个Player对象并将其保持在内部。现在把所有玩家放在一个数组中,你可以轻松排序。

[players sortUsingComparator: ^(Player *p1, Player *p2){
    if (p1.points < p2.points)
        return NSOrderedAscending;   
    else if(p1.points > p2.points)
        return NSOrderedDescending 
    return NSOrderedSame;
}];