我想弄清楚对 CGPoint 数组进行排序的最快/最干净的方法是什么。我想我可以使用循环来实现这一点,但这可能不是最快的,我希望这不是最干净的方法。我想获取一个随机 CGPoints 数组,并按最小 x 坐标到最大,或最小 x 和 y 坐标到最大对它们进行排序。
最佳答案
在 Chuck 做出正确评论后,我使用 sortUsingComparator 方法更新了答案:
这里是带有示例数据的完整代码:
首先我们生成 100 个随机值,我们将这些值输入到数组中:
NSMutableArray *testArray = [[NSMutableArray alloc] initWithCapacity:100];
for (int i=0; i<100; i++) {
CGPoint testPoint = CGPointMake(arc4random()%100, arc4random()%100);
[testArray addObject:[NSValue valueWithCGPoint:testPoint]];
}
下面是对数组进行排序的实际代码:
[testArray sortUsingComparator:^(id firstObject, id secondObject) {
CGPoint firstPoint = [firstObject CGPointValue];
CGPoint secondPoint = [secondObject CGPointValue];
return firstPoint.x>secondPoint.x;
}];
最后我们可以通过打印来验证数组是否已排序:
NSLog(@"%@",testArray);
关于objective-c - 对 CGPoints 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10708401/