Search code examples
iossortingnsarraycgpointnsvalue

iOS: Sorting NSArray of NSValue wrapping CGPoint


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];

Solution

  • 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;
        }];