Objective-c在数组中对Key数组进行排序

时间:2011-06-20 13:44:09

标签: iphone objective-c arrays sorting nsmutablearray

假设我有一个从文件加载的NSMutableArray:

searchTermsArray = [[NSMutableArray alloc] initWithContentsOfFile: yourArrayFileName];

这个数组项内部是关键对象

for (int i=0; i<[searchTermsArray count]; i++) {
            NSLog(@"for array item %d: %@ - %@",i,[[searchTermsArray objectAtIndex:i] objectForKey:@"title"], [[searchTermsArray objectAtIndex:i] objectForKey:@"theCount"] );
        }

(这意味着每个数组元素(item)都有2个键值:

searchTermsArray [0] = title(string),theCount(也是一个字符串,但是由整数组成)

问题:如何根据“theCount”值将“searchTermsArray”数组从高到低排序?

(我正在查看以下代码,但它不符合结构/语法)

NSSortDescriptor *Sorter = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:NO];
        [searchTermsArray sortUsingDescriptors:[NSArray arrayWithObject:Sorter]];
        [Sorter release];

3 个答案:

答案 0 :(得分:3)

您是否应该根据theCount密钥进行排序?

NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:@"theCount" ascending:NO];
[searchTermsArray sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];

答案 1 :(得分:2)

我不确定是否有更好的方法。但这件事有效。

NSInteger intSort(id param1, id param2, void *context) {

    NSDictionary *dict1 = (NSDictionary *)param1;
    NSDictionary *dict2 = (NSDictionary *)param2;

    NSInteger dict1KeyCount = [[dict1 objectForKey:@"count"] intValue];
    NSInteger dict2KeyCount = [[dict2 objectForKey:@"count"] intValue];

    if (dict1KeyCount < dict2KeyCount) {
        return NSOrderedAscending;
    }else if (dict1KeyCount > dict2KeyCount) {
        return NSOrderedDescending;
    }else {
        return NSOrderedSame;
    }
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"two", @"title", @"2", @"count", nil],
                             [NSDictionary dictionaryWithObjectsAndKeys:@"three", @"title", @"3", @"count", nil],
                                [NSDictionary dictionaryWithObjectsAndKeys:@"one", @"title", @"1", @"count", nil], nil];

    NSArray *sortedArray = [array sortedArrayUsingFunction:intSort context:NULL];

    for (NSDictionary *dict in sortedArray) {
        NSLog(@"%d", [[dict objectForKey:@"count"] intValue]);
    }

    [super viewDidLoad];
}

答案 2 :(得分:0)

NSSortDescriptor通常用于对类的对象进行排序。您传递该类中的属性名称以与其他属性进行比较。 由于您在数组中的内容实际上似乎是NSDictionary,因此NSSortDescriptor可能不是解决此问题的最佳方法。此外,你在字典中的对象必须有一个类型,所以如果我是你,我会尝试用一种经典的方法对数组进行排序。