3

Qeustion: Pretty much as stated in the title. I looked over the internet but cannot find anything that is easy to understand. I have NSArray that contains many NSValue. Those NSValue each hold a CGPoint. I want to sort them by x then by y second.

Some code :

NSValue * valuePointObject = [NSValue valueWithCGPoint:CGPointMake(x, y)];
NSArray *array = [[NSArray alloc] initWithObjects: valuePointObject, valuePointObject2, ..., nil];
Byte
  • 2,920
  • 3
  • 33
  • 55

2 Answers2

10

To sort the values you'll have to 'unbox' them to CGPoints again. The code may be like:

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;
    }];
Vladimir
  • 170,431
  • 36
  • 387
  • 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;
    }];
TegRa
  • 519
  • 3
  • 10