问题
im working with a project , where i receive an array of object, each object has a description of type string, and a value of type CGfloat. i need to sort them by value increasingly, and store them in a dicitonary. i tried this solution, but it didn't work. How do I sort an NSMutableArray with custom objects in it? any idea how to do it?
for (PNPieChartDataItem *item in items) {// didnt work
NSArray *sortedArray;
sortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
CGFloat first = [(PNPieChartDataItem*)a value];
CGFloat second = [(PNPieChartDataItem*)b value];
return [first compare:second];
}];
}
回答1:
You don't need a for loop, sortedArrayUsingComparator
iterates on values to compare:
NSArray *sortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
CGFloat first = [(PNPieChartDataItem*)a value];
CGFloat second = [(PNPieChartDataItem*)b value];
return [first compare:second];
}];
}
Use sortedArray
.
来源:https://stackoverflow.com/questions/50286901/sorting-an-array-of-object-with-respect-to-the-float-value