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?

1

2 Answers 2

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];
Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.