简体   繁体   中英

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

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:

@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
  • sortedArrayUsingFunction:context:
  • sortedArrayUsingFunction:context:hint:
  • sortedArrayUsingDescriptors:
  • sortedArrayUsingSelector:
  • sortedArrayUsingComparator:
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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