我有一个nsmutable数组,并且该近50 -60个对象的名称不同,我可以按字母顺序对该数组进行排序吗(有可能吗,怎么办?)
For a simple sort like this, I like to use sort descriptors.
Suppose you have an mutable array of objects whose class has a name
NSString property:
NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
Absolutely, you can use sortUsingSelector:
for this:
[myArray sortUsingSelector:@selector(compare:)];
If your array has custom objects, then you will need to implement a sorting method on those objects:
@implementation myCustomObject
...
-(NSComparisonResult) compare:(myCustomObject*) other {
return [self.name compare:other.name];
}
@end
TechZen's approach works well, but it would work better if you used NSSortDescriptor's +sortDescriptorWithKey:ascending:selector:, passing "localizedCompare:" as the selector. This way, the sorting is localized to the user's language, which can make a big difference in string comparison.
myArray=[myDict keysSortedByValueUsingSelector:@selector(compare:)];
只是为我工作!
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.