I am having a nsmutable array and in that nearly 50 -60 object having different names ,and can i sort this array in alphabetical order (Is it possible, How?)
Asked
Active
Viewed 1.3k times
1
4 Answers
14
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]];

TechZen
- 64,370
- 15
- 118
- 145
-
This will start with "W" and not with "A". How to start with "A"? – Jonathan Gurebo Aug 16 '13 at 20:20
-
I got ascending order first CAPS and small letters. Like "A to Z" and then "a to z". What I need to do. – Mathi Arasan Aug 11 '15 at 06:24
8
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

Jacob Relkin
- 161,348
- 33
- 346
- 320
2
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.

Joshua Nozzi
- 60,946
- 14
- 140
- 135
0
myArray=[myDict keysSortedByValueUsingSelector:@selector(compare:)];
Simply Worked for me!

royemi
- 1