iOS:对NSValue包装CGPoint的NSArray进行排序

时间:2012-04-19 15:17:52

标签: ios sorting nsarray cgpoint nsvalue

Qeustion :几乎与标题中所述相同。我查看了互联网,但找不到任何易于理解的内容。我NSArray包含许多NSValue。那些NSValue每个都持有CGPoint。我希望按x然后按y秒排序。

部分代码

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

2 个答案:

答案 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;
    }];