0

I have an object called Station in my system with these attributes:

@interface Station : NSObject {
NSString *stationID;
NSString *callsign;
NSString *stationState;
}

I also have an NSMutableArray containing 20 'Station' objects as defined above.

I need to define a method which can can sort this array in 2 ways: 1) By stationID 2) By callsign

Can someone please explain how I can do this?

dpigera
  • 3,339
  • 5
  • 39
  • 60
  • Duplicate of [How to sort an NSMutableArray with custom objects in it?](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it) – Georg Schölly Aug 16 '10 at 05:32

2 Answers2

3

I'd use

NSInteger stationsSort( Station *station1, Station *station2, void *context) {
    if ( station1_greater_than_station2 )   {
        return NSOrderedDescending;
    }

    if ( station1_less_than_station2 ) {
        return NSOrderedAscending;
    }

    return NSOrderedSame;   
}

[myArray sortedArrayUsingFunction:stationsSort context:nil];
kovpas
  • 9,553
  • 6
  • 40
  • 44
1

Have a look at NSPredicates. This can be used for query and sorting objects in Arrays.

Examples are here as well. http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html

And NSSortDescriptor - With examples. http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html

John Ballinger
  • 7,380
  • 5
  • 41
  • 51