简体   繁体   中英

Objective-C Sort NSMutableArray of Objects by a specific Object attribute

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?

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];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM