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
Using sortUsingComparator
or sortUsingFunction
messages on the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With