views:

130

answers:

2

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?

+1  A: 

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
+2  A: 

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
I would recommend return signature is NSComparisionResult
vodkhang
vodkhang, I agree, my mistake.
kovpas