4

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

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

Comments

7

Using sortUsingComparator or sortUsingFunction messages on the class.

2 Comments

how to use sortUsingComparator
@WangYang: check out the link I posted. there are examples over there using those messages.
-1

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.

2 Comments

-1 Do you honestly think implementing your own bubble sort is better than using Foundation's built in sorting algorithm?
Heck no, it's just one way of doing it. It's been awhile, I would comment that using NSSortDescriptor for all key's is a much better solution. Please note though, this is the very first thing I did mention in my answer and I also provided a list of built-in methods. Specifically, sortedArrayUsingDescriptors:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.