IOS: NSArray collation for NSValue CGPoint packaging

Qeustion : To a large extent, as indicated in the title. I browsed the internet but cannot find anything that is easy to understand. I have NSArrayone that contains a lot NSValue. Those NSValuecontain a CGPoint. I want to sort them by x, and then ysecond.

Some code :

NSValue * valuePointObject = [NSValue valueWithCGPoint:CGPointMake(x, y)];
NSArray *array = [[NSArray alloc] initWithObjects: valuePointObject, valuePointObject2, ..., nil];
+3
source share
2 answers

To sort the values, you have to unzip them again in CGPoints. The code may be as follows:

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;
    }];
+9
source
    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;
    }];
+4
source

All Articles