views:

162

answers:

2

I've seen examples of something like

[someArray sortUsingSelector:@selector(compare:)];

I'm looking for an example that stores a collection of UIViews and I'd like to sort them in ascending or descending order based on tags I assume programatically when a new UIView is created.

If someone could provide a code example or instructions that would be fantastic

+1  A: 
- (NSComparisonResult)compareTags:(UIView *)view {
    if ([self tag] == [view tag]) return NSOrderedSame;
    if ([self tag] > [view tag]) return NSOrderedDescending;
    return NSOrderedAscending;
}

Assuming I got the ordering right, that is, and the methods for this use would have to be on UIView (easily done with a category). There are several other ways of getting the same result, see the docs Sorting Arrays.

Paul Lynch
Thanks for this, I've gone for the NSSortDescriptor solution but I appreciate sound reply!
Chris
+1  A: 

NSArray provides a number of methods to sort an array (all listed under the "Sorting" header in the NSArray docs). You can define a function, a method or a sort descriptor to compare the views based on their tags for sorting. For example, here's an implementation using NSSortDescriptor:

NSSortDescriptor *ascendingSort = [[NSSortDescriptor alloc] initWithKey:@"tag" ascending:YES];
NSSortDescriptor *descendingSort = [[NSSortDescriptor alloc] initWithKey:@"tag" ascending:NO];
NSArray *sortedArray = [someArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:ascendingSort]];
Chuck
Thanks, more classes to read up on!
Chris
Hi Chuck I'm wondering if you could further assist, I'm curious whether this sort will work with using a UIView's frame.origin.y property (or any property by that matter), I am struggling to understand the way sorting works in Objective-C, I'm sure I'll get there, just hoping to do so sooner rather then later! Thanks
Chris