简体   繁体   English

如何对NSMutableArray进行排序

[英]How to sort an NSMutableArray

my class like this: 我的班级是这样的:

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

I created an NSMutableArray that contains several of these car objects, how to sort the NSMutableArray by price 我创建了一个NSMutableArray,其中包含几个这样的汽车对象,如何按价格对NSMutableArray进行排序

Using a comparator it may look like this: 使用比较器可能如下所示:

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);

And this is my Car class: 这是我的Car类:

@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

Sorting an array has built-in junk you should use due to fast enumeration. 排序数组有内置垃圾,你应该使用快速枚举。 For Dictionary keys, I use a bubble sort like this: 对于字典键,我使用这样的冒泡排序:

- (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;
}

Then you can use this function like so: 然后您可以像这样使用此功能:

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

For your reference here is a list of built-in array sorting methods: 这里有一个内置数组排序方法列表供您参考:

  • sortedArrayHint sortedArrayHint
  • sortedArrayUsingFunction:context: sortedArrayUsingFunction:背景:
  • sortedArrayUsingFunction:context:hint: sortedArrayUsingFunction:背景:提示:
  • sortedArrayUsingDescriptors: sortedArrayUsingDescriptors:
  • sortedArrayUsingSelector: sortedArrayUsingSelector:
  • sortedArrayUsingComparator: sortedArrayUsingComparator:
  • sortedArrayWithOptions:usingComparator: sortedArrayWithOptions:usingComparator:

For completeness in response to my comment below here is how you would use a sort descriptory on a dictionary of keys or any array: 为了完整性以回应我在下面的评论,这里是如何在键或任何数组的字典上使用排序描述:

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

Enjoy. 请享用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM