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开发者_如何学C' 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
精彩评论