Qeustion :几乎与标题中所述相同。我查看了互联网,但找不到任何易于理解的内容。我NSArray
包含许多NSValue
。那些NSValue
每个都持有CGPoint
。我希望按x
然后按y
秒排序。
部分代码:
NSValue * valuePointObject = [NSValue valueWithCGPoint:CGPointMake(x, y)];
NSArray *array = [[NSArray alloc] initWithObjects: valuePointObject, valuePointObject2, ..., nil];
答案 0 :(得分:9)
要对值进行排序,您必须再次将它们“拆箱”到CGPoints。代码可能如下:
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSValue *obj1, NSValue *obj2) {
CGPoint p1 = [obj1 CGPointValue];
CGPoint p2 = [obj2 CGPointValue];
if (p1.x == p2.x) return p1.y < p2.y;
return p1.x < p2.x;
}];
答案 1 :(得分:4)
array = [array sortedArrayUsingComparator:^NSComparisonResult(NSValue *obj1, NSValue *obj2) {
if (obj1.CGPointValue.x < obj2.CGPointValue.x) {
return NSOrderedAscending;
}
if (obj1.CGPointValue.x > obj2.CGPointValue.x) {
return NSOrderedDescending;
}
if (obj1.CGPointValue.y < obj2.CGPointValue.y) {
return NSOrderedAscending;
}
if (obj1.CGPointValue.y > obj2.CGPointValue.y) {
return NSOrderedDescending;
}
return NSOrderedSame;
}];