Objective-c – Objective C – Sorting by property


Is there anyway I can sort a NSMutableArray that contains UIImageView by the UIImageView's frame.origin.y value?

Trying to do the sort before adding the view to make sure the stacking order is correct.

Thank you,

Best Solution

You could provide a compare selector:

NSInteger intSort(id num1, id num2, void* context)
    int v1 = [num1 intValue];
    int v2 = [num2 intValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
        return NSOrderedSame;

This method compares NSNumber objects.
You would need to change it to change your view controller coordinates.

To set this compare selector:

NSArray* sortedArray; 
sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

This is an example from the Apple documentation.

Here is a similar (but for alphabetical sorting) question.