如何排序NSMutableArray?需要进行代码审查

时间:2011-11-19 01:40:09

标签: objective-c sorting nsmutablearray

晚上好。

此代码有效。它通过Suit和Card Value对一系列卡片进行排序。这也是非常蛮力。你能推荐一个更好的方法吗? Objective-C是否有助于处理被排序的对象本身有多个字段的情况,排序取决于哪些字段?

-(void) sort: (NSMutableArray *) deck {        
    NSUInteger count = [deck count];

    Card *thisCard;
    Card *nextCard;

    int this;
    int next;

    BOOL stillSwapping = true;

    while (stillSwapping) {

        stillSwapping = false;

        for (NSUInteger i = 0; i < count; ++i) {
            this = i;
            next = i+1;

            if (next < count) {

                thisCard = [deck objectAtIndex:this];
                nextCard = [deck objectAtIndex:next];

                if ([thisCard suit] > [nextCard suit]) {                        
                    [deck exchangeObjectAtIndex:this withObjectAtIndex:next];
                    stillSwapping = true;
                } 


                if ([thisCard suit] == [nextCard suit]) {
                    if ([thisCard value] > [nextCard value]) {
                        [deck exchangeObjectAtIndex:this withObjectAtIndex:next];
                        stillSwapping = true;
                    } 
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:7)

您有几种选择。

最简单的方法是在-compare:上定义方法Card,该方法返回NSComparisonResult。如果按套装和值排序是对Card进行排序的“标准”方式,则这是首选。如果你已经这样做了,那么你的整个排序方法可以变成

[deck sortUsingSelector:@selector(compare:)];

如果您不想这样做,可以使用NSSortDescriptor个数组,一个用于套装,一个用于值。

[deck sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"suit" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:@"value"] ascending:YES], nil]];

如果由于某种原因无效,您可以尝试-sortUsingComparator:

[deck sortUsingComparator:^NSComparisonResult(Card *obj1, Card *obj2) {
    int suit1 = [obj1 suit];
    int suit2 = [obj2 suit];
    if (suit1 > suit2) {
        return NSOrderedDescending;
    } else if (suit1 < suit2) {
        return NSOrderedAscending;
    } else {
        id value1 = [obj1 value];
        id value2 = [obj2 value];
        if (value1 > value2) {
            return NSOrderedDescending;
        } else if (value1 < value2) {
            return NSOrderedAscending;
        } else {
            return NSOrderedSame;
        }
    }
}