sorting an array of object with respect to the float value [duplicate]

限于喜欢 提交于 2019-12-11 15:26:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!