根据流行度排序NS(Mutable)数组

时间:2012-05-08 13:59:46

标签: iphone ios

我知道如何按字母顺序对数组进行排序,但我希望通过其中对象的流行度来对NSMutableArray进行排序。想象一个包含以下对象的数组:

  • A
  • C
  • A

我想按受欢迎程度对这些对象进行排序,并创建一个这样的数组:

  • A
  • A
  • C

有一个好的,快速的方法吗?也许是NSSortDescriptor的关键? (找不到)

由于

4 个答案:

答案 0 :(得分:1)

简而言之,为简洁起见,我使用了新的数组文字语法。

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSArray *ar = @[@"B", @"A", @"C", @"B", @"B", @"A"];
        NSCountedSet *countedSet = [NSCountedSet setWithArray:ar];
        NSArray *sorted = [ar sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSInteger diff = [countedSet countForObject:obj1] - [countedSet countForObject:obj2];
            if (diff < 0)
                return NSOrderedDescending;
            else if (diff > 0)
                return NSOrderedAscending;
            else
                return NSOrderedSame;
        }];
        NSLog(@"%@", ar);
        NSLog(@"%@", sorted);
    }
    return 0;
}

输出

2012-05-08 07:25:18.465 Sort[20434:303] (
    B,
    A,
    C,
    B,
    B,
    A
)
2012-05-08 07:25:18.468 Sort[20434:303] (
    B,
    B,
    B,
    A,
    A,
    C
)

答案 1 :(得分:0)

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"theSortKey"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

也看到这个帖子

How to sort an NSMutableArray with custom objects in it?

答案 2 :(得分:0)

这应该适合你。

NSArray *array = [[NSArray alloc] initWithObjects:@"A", @"A", @"B", @"B", @"B", @"C", nil];
NSMutableDictionary *occurenceOfValues = [[NSMutableDictionary alloc] init];
for (id value in array) {
    NSNumber *count = [occurenceOfValues objectForKey:value];
    [occurenceOfValues setValue:[NSNumber numberWithInt:[count intValue] + 1] forKey:value];
}
NSArray *valuesInOrder = [[[occurenceOfValues keysSortedByValueUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];
NSMutableArray *sortedArray = [[NSMutableArray alloc] initWithCapacity:array.count];
for (id value in valuesInOrder) {
    NSNumber *count = [occurenceOfValues objectForKey:value];
    for (int i = 0; i < [count intValue]; i++) {
        [sortedArray addObject:value];
    }
}
NSLog(@"%@", sortedArray);

控制台输出:

2012-05-08 09:20:15.805 SortArrayPopularity [25206:f803](     B,     B,     B,     一个,     一个,     C )

答案 3 :(得分:0)

我会使用一个字典,它有A,B,C ......作为键,并将默认值设置为0

然后枚举数组并增加相应键的计数。

最后对[dict allKeys];

返回的键数组进行排序