Several simple and effective array sorting methods for IOS, and ios array sorting
// First, use the sortedArrayUsingComparator of the array to call the object in the NSComparator, obj1 and obj2 arrays.
NSComparator cmptr = ^ (id obj1, id obj2 ){
If ([obj1 integerValue]> [obj2 integerValue]) {
Return (NSComparisonResult) NSOrderedDescending;
}
If ([obj1 integerValue] <[obj2 integerValue]) {
Return (NSComparisonResult) NSOrderedAscending;
}
Return (NSComparisonResult) NSOrderedSame;
};
NSArray * sortArray = [[NSArray alloc] initWithObjects: @ "1", @ "3", @ "4", @ "7", @ "8 ", @ "2", @ "6", @ "5", @ "13", @ "15", @ "12", @ "20", @ "28 ", @ "", nil];
// Before sorting
NSMutableString * outputBefore = [[NSMutableString alloc] init];
For (NSString * str in sortArray ){
[OutputBefore appendFormat: @ "];
}
NSLog (@ "Before sorting: % @", outputBefore );
[OutputBefore release];
// First sort
NSArray * array = [sortArray sortedArrayUsingComparator: cmptr];
NSMutableString * outputAfter = [[NSMutableString alloc] init];
For (NSString * str in array ){
[OutputAfter appendFormat: @ "];
}
NSLog (@ "after sorting: % @", outputAfter );
[OutputAfter release];
The second sorting method uses sortedArrayUsingFunction to call the corresponding customSort method. In this method, obj1 and obj2 are the objects in the index group respectively.
NSInteger customSort (id obj1, id obj2, void * context ){
If ([obj1 integerValue]> [obj2 integerValue]) {
Return (NSComparisonResult) NSOrderedDescending;
}
If ([obj1 integerValue] <[obj2 integerValue]) {
Return (NSComparisonResult) NSOrderedAscending;
}
Return (NSComparisonResult) NSOrderedSame;
}
NSArray * sortArray = [[NSArray alloc] initWithObjects: @ "1", @ "3", @ "4", @ "7", @ "8 ", @ "2", @ "6", @ "5", @ "13", @ "15", @ "12", @ "20", @ "28 ", @ "", nil];
// Before sorting
NSMutableString * outputBefore = [[NSMutableString alloc] init];
For (NSString * str in sortArray ){
[OutputBefore appendFormat: @ "];
}
NSLog (@ "Before sorting: % @", outputBefore );
[OutputBefore release];
NSArray * array = [sortArray sortedArrayUsingFunction: customSort context: nil];
NSMutableString * outputAfter = [[NSMutableString alloc] init];
For (NSString * str in array ){
[OutputAfter appendFormat: @ "];
}
NSLog (@ "after sorting: % @", outputAfter );
[OutputAfter release];
Third, use sortUsingDescriptors to call NSSortDescriptor
NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey: @ "price" ascending: NO]; // where price is the attribute of the object in the array, it is more concise and convenient to store objects in arrays.
NSArray * sortDescriptors = [[NSArray alloc] initWithObjects: & sortDescriptor count: 1];
[_ TotalInfoArray sortUsingDescriptors: sortDescriptors];
[_ AirListView refreshTable: _ totalInfoArray];
[SortDescriptor release];
[SortDescriptors release];