dav*_*Mac 2 arrays sorting objective-c nsarray cgpoint
我试图弄清楚对CGPoints数组进行排序的最快/最干净的方法是什么.我想我可以使用循环实现这一点,但这可能不是最快的,我希望它不是最干净的方式.我想取一个随机CGPoints数组,并按最小x坐标到最大,或最小x 和 y坐标到最大排序.
在Chuck的正确评论之后,我使用sortUsingComparator方法更新了答案:
以下是包含示例数据的完整代码:
首先,我们生成100个随机值,然后输入到Array:
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]];
}
Run Code Online (Sandbox Code Playgroud)
这是对数组进行排序的实际代码:
[testArray sortUsingComparator:^(id firstObject, id secondObject) {
CGPoint firstPoint = [firstObject CGPointValue];
CGPoint secondPoint = [secondObject CGPointValue];
return firstPoint.x>secondPoint.x;
}];
Run Code Online (Sandbox Code Playgroud)
最后我们可以通过打印来验证数组是否已排序:
NSLog(@"%@",testArray);
Run Code Online (Sandbox Code Playgroud)