如何对NSMutableArray进行排序

4

我的类是这样的:

car
--------------
price
color

我创建了一个NSMutableArray,其中包含多个汽车对象,请问如何按价格对NSMutableArray进行排序?
3个回答

8
使用比较器,代码可能如下所示:

NSMutableArray类的参考

NSMutableArray *cars= [NSMutableArray arrayWithCapacity:5];
[cars addObject:[[[Car alloc] initWithColor:@"blue" price:30000.0] autorelease]];
[cars addObject:[[[Car alloc] initWithColor:@"yellow" price:35000.0] autorelease]];
[cars addObject:[[[Car alloc] initWithColor:@"black" price:29000.0] autorelease]];
[cars addObject:[[[Car alloc] initWithColor:@"green" price:42000.0] autorelease]];
[cars addObject:[[[Car alloc] initWithColor:@"white" price:5000.0] autorelease]];


[cars sortUsingComparator:^NSComparisonResult(Car *car1, Car *car2) {
    if (car1.price < car2.price)
        return (NSComparisonResult)NSOrderedAscending;
    if (car1.price > car2.price)
        return (NSComparisonResult)NSOrderedDescending;
    return (NSComparisonResult)NSOrderedSame;

}];

NSLog(@"%@", cars);

这是我的汽车类:

@interface Car : NSObject
@property (nonatomic, copy)NSString *colorName;
@property (nonatomic) float price;
-(id)initWithColor:(NSString *)colorName price:(float)price;
@end

@implementation Car
@synthesize colorName = colorName_;
@synthesize price = price_;

-(id)initWithColor:(NSString *)colorName price:(float)price
{
    if (self = [super init]) {
        colorName_ = [colorName copy];
        price_ = price;
    }
    return self;
}

- (void)dealloc {
    [colorName_ release];
    [super dealloc];
}

-(NSString *)description
{
    return [NSString stringWithFormat:@"%@ %f", self.colorName, self.price];
}
@end

7

如何使用sortUsingComparator函数 - WangYang
@WangYang:看看我发布的链接。那里有使用这些消息的示例。 - Pablo Santa Cruz

-1

对于数组的排序,由于快速枚举,建议使用内置的垃圾处理机制。对于字典键,我使用类似以下的冒泡排序:

- (NSMutableArray*) bubbleSortDictKeys:(NSDictionary*)dict {

    if(!dict)
        return nil;

    NSMutableArray *sortedKeys = [NSMutableArray arrayWithArray: [dict allKeys]];

    if([sortedKeys count] <= 0)
        return nil;
    else if([sortedKeys count] == 1)
        return sortedKeys; 

    int n = [sortedKeys count] -1, i;
    BOOL swapped = YES;

    NSString *key1,*key2;
    NSComparisonResult result;

    while(swapped)
    {
        swapped = NO;
        for( i = 0; i < n; i++ )
        {
            key1 = [sortedKeys objectAtIndex: i];
            key2 = [sortedKeys objectAtIndex: i + 1];


            result = [key1 compare: key2 options: NSCaseInsensitiveSearch];
            if(result == NSOrderedDescending)
            {
                [key1 retain]; [key2 retain];

                [sortedKeys exchangeObjectAtIndex:i withObjectAtIndex:i+1];

                [key1 release]; [key2 release];

                swapped = YES;
            }
        }
    }

    return sortedKeys;
}

然后你可以这样使用这个函数:

NSEnumerator *keys = [[self bubbleSortDictKeys:dict] objectEnumerator];

以下是一些内置的数组排序方法供您参考:

  • sortedArrayHint
  • sortedArrayUsingFunction:context:
  • sortedArrayUsingFunction:context:hint:
  • sortedArrayUsingDescriptors:
  • sortedArrayUsingSelector:
  • sortedArrayUsingComparator:
  • sortedArrayWithOptions:usingComparator:

为了完整回应下面的评论,这里介绍如何在键值字典或任何数组上使用排序描述符:

NSArray *arrayToSort, *sortedArray;
arrayToSort = [NSArray arrayWithObjects:car1, car2, car3, nil];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"color"  ascending:YES];
sortedArray = [arrayToSort sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
// Use your sortedArray

享受吧。


1
你真的认为自己实现冒泡排序比使用Foundation内置的排序算法更好吗? - JeremyP
当然不是,这只是其中一种方法。已经有一段时间了,我想评论一下使用NSSortDescriptor对所有键进行排序是一个更好的解决方案。请注意,这是我在答案中提到的第一件事,并且我还提供了一些内置方法的列表,特别是sortedArrayUsingDescriptors:。 - Arvin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接