方法一:在数组的对象里增加比较方法,例如Person类型的数组,想按生日来排序,那么首先在Person类里增加下面的方法,注意返回值的类型。
- (NSComparisonResult)compare:(Person *)otherObject { return [self.birthDate compare:otherObject.birthDate]; }当需要对这个数组进行排序时,写下面的代码:
NSArray *sortedArray; sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
方法二:NSSortDescriptor (较好)
首先定义一个比较器,规定按birthDate字段来排序NSSortDescriptor *sortDescriptor; sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES] autorelease]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSArray *sortedArray; sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];
方法三:Blocks (最好)
10.6以后,可以使用代码段的方法。NSArray *sortedArray; sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { NSDate *first = [(Person*)a birthDate]; NSDate *second = [(Person*)b birthDate]; return [first compare:second]; }];