3

Qeustion : 和标题中说的差不多。我查看了互联网,但找不到任何易于理解的内容。我有NSArray包含很多NSValue. 那些NSValue每个持有一个CGPoint. 我想xy秒对它们进行排序。

一些代码

NSValue * valuePointObject = [NSValue valueWithCGPoint:CGPointMake(x, y)];
NSArray *array = [[NSArray alloc] initWithObjects: valuePointObject, valuePointObject2, ..., nil];
4

2 回答 2

10

要对值进行排序,您必须再次将它们“拆箱”到 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;
    }];
于 2012-04-19T15:22:54.313 回答
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;
    }];
于 2012-04-19T15:25:25.443 回答