[英]Objective-C Sort NSMutableArray of Objects by a specific Object attribute
I have an object called Station in my system with these attributes: 我的系统中有一个名为Station的对象,具有以下属性:
@interface Station : NSObject {
NSString *stationID;
NSString *callsign;
NSString *stationState;
}
I also have an NSMutableArray containing 20 'Station' objects as defined above. 我也有一个NSMutableArray,其中包含20个以上定义的“ Station”对象。
I need to define a method which can can sort this array in 2 ways: 1) By stationID 2) By callsign 我需要定义一个方法,该方法可以通过两种方式对该数组进行排序:1)通过stationID 2)通过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. 看看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
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html
And NSSortDescriptor - With examples. 和NSSortDescriptor-带有示例。 http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.