Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 294
WangYang Avatar asked Dec 10 '22 10:12

WangYang


2 Answers

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
like image 80
vikingosegundo Avatar answered Dec 26 '22 12:12

vikingosegundo


Using sortUsingComparator or sortUsingFunction messages on the class.

like image 43
Pablo Santa Cruz Avatar answered Dec 26 '22 13:12

Pablo Santa Cruz