方法一:在數(shù)組的對象里增加比較方法寸莫,例如Person類型的數(shù)組,想按生日來排序,那么首先在Person類里增加下面的方法熬甫,注意返回值的類型猎塞。
- (NSComparisonResult)compare:(Person *)otherObject
{
return [self.birthDate compare:otherObject.birthDate];
}
當(dāng)需要對這個數(shù)組進行排序時试读,寫下面的代碼:
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
方法二:NSSortDescriptor (較好)
首先定義一個比較器,規(guī)定按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];
}];