Sorting array(NSArray) in descending order - objective-c

I have a array of NSString objects which I have to sort by descending.
Since I did not find any API to sort the array in descending order I approached by following way.
I wrote a category for NSString as listed bellow.
- (NSComparisonResult)CompareDescending:(NSString *)aString
{
NSComparisonResult returnResult = NSOrderedSame;
returnResult = [self compare:aString];
if(NSOrderedAscending == returnResult)
returnResult = NSOrderedDescending;
else if(NSOrderedDescending == returnResult)
returnResult = NSOrderedAscending;
return returnResult;
}
Then I sorted the array using the statement
NSArray *sortedArray = [inFileTypes sortedArrayUsingSelector:#selector(CompareDescending:)];
Is this right solution? is there a better solution?

You can use NSSortDescriptor:
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:#selector(localizedCompare:)];
NSArray* sortedArray = [inFileTypes sortedArrayUsingDescriptors:#[sortDescriptor]];
Here we use localizedCompare: to compare the strings, and pass NO to the ascending: option to sort in descending order.

or simplify your solution:
NSArray *temp = [[NSArray alloc] initWithObjects:#"b", #"c", #"5", #"d", #"85", nil];
NSArray *sortedArray = [temp sortedArrayUsingComparator:
^NSComparisonResult(id obj1, id obj2){
//descending order
return [obj2 compare:obj1];
//ascending order
return [obj1 compare:obj2];
}];
NSLog(#"%#", sortedArray);

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"length" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[wordsArray sortUsingDescriptors:sortDescriptors];
Using this code we can sort the array in descending order on the basis of length.

Related

Sorting an NSArray in reverse order

NSArray* sortedArray = [myArray sortedArrayUsingSelector:#selector(compare:)];
Just wondering how I can sort this array of numbers in descending order?
Either use the method that allows you to pass a block as a comparator and implement a comparator that reverses the objects (returns NSOrderedAscending for NSOrderedDescending and vice versa)....
... or:
NSArray *reversed = [[[myArray sortedArrayUsingSelector:#selector(compare:)] reverseObjectEnumerator] allObjects];
Sorry. Derped the most important part.
Use NSSortDescriptor
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: #"self" ascending: NO];
NSArray *temp = [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
I like to use the sortedArrayUsingFunction: method which gives full control of how the array is sorted. Then to reverse the results return the negative value of what you would have returned.
NSInteger myCompare (id obj1, id obj2, void *context) {
int retval = [obj1 compare:obj2 options:NSNumericSearch];
retval = -retval; // now it's sorted reverse
return retval;
}
...
NSArray *arr = #[#"foo20zz", #"foo7zz", #"foo100zz"];
NSArray *sarr = [arr sortedArrayUsingFunction:myCompare context:NULL];
NSLog(#"sarr is %#", sarr);

Sorting NSMutableArray by date

I want to sort a mutable array by date. My array contains several dict with keys say:key1,key2,birthday.Now, I have to sort by its birthday key:
I know that this can be done using:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"birthday" ascending:YES];
[myArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
But my problem is that I want to sort only those arrays, which don’t contain empty birthday field. My array will contains several empty birthday fields. I don’t want to sort those.
Finally I have to load these in table view through [self.mTable reloadData];.
First collect the indices of all objetcs without a birthday.
NSIndexSet *indexSet = [NSIndexSet indexSet];
[array enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop)
{
if(![[dict allKeys] containsObject:#"birthday"]){
[indexSet addIndex:idx];
}
}];
Now remove them from the original array
[array removeObjectsAtIndexes:indexSet];
Using a comparator block, sorting could look like
[array sortUsingComparator: ^(NSDictionary *d1, NSDictionary *d2) {
NSDate *date1 = [d1 objectForKey:#"birthday"];
NSDate *date2 = [d2 objectForKey:#"birthday"];
return [date1 compare:date2]
}
Create a different array to back your table view like this:
NSDictionary* obj1 = [NSDictionary dictionaryWithObject: [NSDate date] forKey: #"birthday"];
NSDictionary* obj2 = [NSDictionary dictionaryWithObject: [NSDate dateWithTimeIntervalSince1970: 0] forKey: #"birthday"];
NSDictionary* obj3 = [NSDictionary dictionaryWithObject: #"wow" forKey: #"no_birthday"];
NSArray* all = [NSArray arrayWithObjects: obj1, obj2, obj3, nil];
NSArray* onlyWithBirthday = [all valueForKeyPath: #"#unionOfObjects.birthday"];
And if you need the full objects for the table view, continue with this code:
NSPredicate* filter = [NSPredicate predicateWithFormat: #"SELF.birthday IN %#", onlyWithBirthday];
NSArray* datasource = [all filteredArrayUsingPredicate: filter];
Then you can apply your sort method of choice.

Sort NSMutableArray with strings that contain numbers?

I have a NSMutableArray and it has the users high scores saved into it. I want to arrange the items numerically (the numbers are stored in NSStrings.)Example:4,2,7,8To2,4,7,8What is the simplest way to do this if the data is stored in NSStrings?
This code will do it:
//creating mutable array
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:#"4", #"2", #"7", #"8", nil];
//sorting
[myArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
return [str1 compare:str2 options:(NSNumericSearch)];
}];
//logging
NSLog(#"%#", myArray);
It uses blocks, make sure your target OS supports that (It's 4.0 for iOS and 10.6 for OSX).
This code works. I tried it:
NSMutableArray *unsortedHighScores = [[NSMutableArray alloc] initWithObjects:#"4", #"2", #"7", #"8", nil];
NSMutableArray *intermediaryArray = [[NSMutableArray alloc] init];
for(NSString *score in unsortedHighScores){
NSNumber *scoreInt = [NSNumber numberWithInteger:[score integerValue]];
[intermediaryArray addObject:scoreInt];
}
NSArray *sortedHighScores = [intermediaryArray sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"%#", sortedHighScores);
The output is this:
2
4
7
8
If you have any questions about the code, just ask in the comments. Hope this helps!
The NSMutableArray method sortUsingSelector: should do it:
[scoreArray sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)]
should do it.
If the array is of nsdictionaries conaining numeric value for key number
isKeyAscending = isKeyAscending ? NO : YES;
[yourArray sortUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
NSString *str1 = [obj1 objectForKey:#"number"];
NSString *str2 = [obj2 objectForKey:#"number"];
if(isKeyAscending) { //ascending order
return [str1 compare:str2 options:(NSNumericSearch)];
} else { //descending order
return [str2 compare:str1 options:(NSNumericSearch)];
}
}];
//yourArray is now sorted
The answer from Darshit Shah make it smootly
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:#"rank" ascending:YES selector:#selector(localizedStandardCompare:)];

NSSortDescriptor sort with number as string?

Got a an Array full of dictionary likes this:
(
{ order = "10";
name = "David"
};
{ order = "30";
name = "Jake";
};
{ order = "200";
name = "Michael";
};
)
When i'm using NSSortDescriptor like the code below it only sorts regarding to the first char so 200 is lower then 30. I can of course change the "order" object into a NSNumber instead of string and it would work. But is there a way to sort a string as int values without changing the source object?
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"norder" ascending:YES];
[departmentList sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
Update:
Thanks to bandejapaisa.
Here is the a working version for iOS 5 (Xcode where compalining).
NSArray *sortedArray;
sortedArray = [departmentList sortedArrayUsingComparator:(NSComparator)^(id a, id b) {
NSNumber *num1 = [NSNumber numberWithInt:[[a objectForKey:#"norder"] intValue]];
NSNumber *num2 = [NSNumber numberWithInt:[[b objectForKey:#"norder"] intValue]];
return [num1 compare:num2];
}];
departmentList = [sortedArray mutableCopy];
Using a NSNumber is overkill. You can save yourself a lot of overhead by doing the following:
NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
return (NSComparisonResult) [obj1 intValue] - [obj2 intValue];
}];
Maybe sort using a comparator instead, or one of the other sorting methods:
NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
NSNumber *num1 = [NSNumber numberWithInt:[obj1 intValue]];
NSNumber *num2 = [NSNumber numberWithInt:[obj2 intValue]];
return (NSComparisonResult)[rank1 compare:num2];
}];
All the above methods need good knowledge in basics to implement, but for the freshers i suggest the most simplest way is to use the native block method, hope this helps
NSArray* sortedArr =[fetchResults sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
int aValue = [[a valueForKey:#"subgroupId"] intValue];
int bValue = [[b valueForKey:#"subgroupId"] intValue];
return aValue>bValue; }];
Happy Coding...

Getting NSDictionary keys sorted by their respective values

I have an NSMutableDictionary with integer values, and I'd like to get an array of the keys, sorted ascending by their respective values. For example, with this dictionary:
mutableDict = {
"A" = 2,
"B" = 4,
"C" = 3,
"D" = 1,
}
I'd like to end up with the array ["D", "A", "C", "B"]. My real dictionary is much larger than just four items, of course.
The NSDictionary Method keysSortedByValueUsingComparator: should do the trick.
You just need a method returning an NSComparisonResult that compares the object's values.
Your Dictionary is
NSMutableDictionary * myDict;
And your Array is
NSArray *myArray;
myArray = [myDict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
Just use NSNumber objects instead of numeric constants.
BTW, this is taken from:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html
NSDictionary has this neat method called allKeys.
If you want the array to be sorted though, keysSortedByValueUsingComparator: should do the trick.
Richard's solution also works but makes some extra calls you don't necessarily need:
// Assuming myDictionary was previously populated with NSNumber values.
NSArray *orderedKeys = [myDictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){
return [obj1 compare:obj2];
}];
Here's a solution:
NSDictionary *dictionary; // initialize dictionary
NSArray *sorted = [[dictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[dictionary objectForKey:obj1] compare:[dictionary objectForKey:obj2]];
}];
The simplest solution:
[dictionary keysSortedByValueUsingSelector:#selector(compare:)]
Here i have done something like this:
NSMutableArray * weekDays = [[NSMutableArray alloc] initWithObjects:#"Sunday",#"Monday",#"Tuesday",#"Wednesday",#"Thursday",#"Friday",#"Saturday", nil];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableArray *dictArray = [[NSMutableArray alloc] init];
for(int i = 0; i < [weekDays count]; i++)
{
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:i],#"WeekDay",[weekDays objectAtIndex:i],#"Name",nil];
[dictArray addObject:dict];
}
NSLog(#"Before Sorting : %#",dictArray);
#try
{
//for using NSSortDescriptor
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"WeekDay" ascending:YES];
NSArray *descriptor = #[sortDescriptor];
NSArray *sortedArray = [dictArray sortedArrayUsingDescriptors:descriptor];
NSLog(#"After Sorting : %#",sortedArray);
//for using predicate
//here i want to sort the value against weekday but only for WeekDay<=5
int count=5;
NSPredicate *Predicate = [NSPredicate predicateWithFormat:#"WeekDay <=%d",count];
NSArray *results = [dictArray filteredArrayUsingPredicate:Predicate];
NSLog(#"After Sorting using predicate : %#",results);
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorting cant be done because of some error" message:[NSString stringWithFormat:#"%#",exception] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert setTag:500];
[alert show];
[alert release];
}