如何对NSMutableArray进行排序

Wan*_*ang 4 cocoa-touch objective-c ios

我的班级是这样的:

car
--------------
price
color
Run Code Online (Sandbox Code Playgroud)

我创建了一个NSMutableArray,其中包含几个这样的汽车对象,如何按价格对NSMutableArray进行排序

Vik*_*ica 8

使用比较器可能如下所示:

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);
Run Code Online (Sandbox Code Playgroud)

这是我的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
Run Code Online (Sandbox Code Playgroud)