How to sort NSMutableArray in ascending order, iPhone? - iphone

I have SQLite Database(DB) and made this to model class and taken the data of DB in NSMutableArray. My DB is similar to this DB.
StudentName | RegisterNumber | DatesOfJoin(DoJ)
I am displaying the DoJ in tableView successfully, but I wanna sort the DatesOfJoin in Ascending order and Descending order in tableView.
Any help would be appreciated and Thanks you in advance.

You can use NSSortDescriptor and sortUsingDescriptors:sortDescriptors to sort a mutable array.
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"DatesOfJoin" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[array sortUsingDescriptors:sortDescriptors];
[sortDescriptor release];

Take a look at the official documentation:
http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSArray_Class/NSArray.html
You got a lot of methods to sort the array:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
- (NSArray *)sortedArrayUsingSelector:(SEL)comparator
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
- (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr

For Desending Order:
NSArray *sorted = [Arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue] < [obj2 intValue]) return NSOrderedDescending;
else return NSOrderedAscending;
}];
For Asending Order:
NSArray *sorted = [Arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue] < [obj2 intValue]) return NSOrderedAscending;
else return NSOrderedDescending;
}];

You can try using :
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"Over here your key" ascending:YES]; //Just write the key for which you want to have sorting & whole array would be sorted.
[self.messageAry sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
[descriptor release];
Hope that works,

NSString *res =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//Sorting an array
NSMutableArray *sortArray = [res valueForKey:#"Year"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:#selector(localizedCompare:)];
yearArray = [sortArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
In Swift 3.0 Version
let sortedCapitalArray = yourArray.sorted {($0 as AnyObject).localizedCaseInsensitiveCompare(($1 as AnyObject)as! String) == ComparisonResult.orderedAscending}

Related

Sorting NSMutableArray with class objects for a peticular object in alphabetical order

I have an array with property class objects like
for (int i=0; i<[eventList count]; i++) {
NSDictionary *EventListDic=[eventList objectAtIndex:i];
eventData.eventID=[EventListDic objectForKey:#"event_id"];
eventData.eventsname=[EventListDic objectForKey:#"title"];
[self.arrEventDataList addObject:eventData];
[eventData release];
}
I want to sort this array for eventData.eventsname key in alphabetical order. I tried out with following functionality, but it is not working. Please suggest me how to do this. Thanks in advance
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:NO];
NSArray *orderedArray = [self.arrEventDataList sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
I want to sort my arrEventDataList sorted by eventsname .
Try this.
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:#"eventsname"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedArray = [arrEventDataList sortedArrayUsingDescriptors:sortDescriptors];
You will have the sorted values. This will sort your arrEventDataList.
Try This One...
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"self" ascending:YES];
NSArray *sortedFloats = [eventData.eventsname sortedArrayUsingDescriptors:
[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
// Put the two arrays into a dictionary as keys and values
NSDictionary *dictID = [NSDictionary dictionaryWithObjects:eventData.eventID forKeys:eventData.eventsname];
// Sort the second array based on the sorted first array
sortedID = [dictID objectsForKeys:sortedFloats notFoundMarker:[NSNull null]];

NSMutableDictionary does not sort correctly

Let i have unsorted NSMutableDictionary
{
A = "3";
B = "2";
C = "4";
}
And i need result to be like:
{
B = "2";
A = "3";
C = "4";
}
How can i achieve this result in objective c.
A simple code implementation will be appreciated.
Not possible with an NSMutableDictionary, it is not a sorted structure. You will have to turn it into an NSArray and then sort that. You will then not have a dictionary structure.
You can not sort NSMutableDictionary by value as #joe and #mavrick3 answer. However if you change there keys and values to NSArray you can do it..
Here is simple implementation..
NSMutableDictionary *results; //dictionary to be sorted
NSMutableDictionary *results; //dict to be sorted
NSArray *sortedKeys = [results keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue])
return (NSComparisonResult)NSOrderedDescending;
if ([obj1 integerValue] < [obj2 integerValue])
return (NSComparisonResult)NSOrderedAscending;
return (NSComparisonResult)NSOrderedSame;
}];
NSArray *sortedValues = [[results allValues] sortedArrayUsingSelector:#selector(compare:)];
//Descending order
for (int s = ([sortedValues count]-1); s >= 0; s--) {
NSLog(#" %# = %#",[sortedKeys objectAtIndex:s],[sortedValues objectAtIndex:s]);
}
//Ascending order
for (int s = 0; s < [sortedValues count]; s++) {
NSLog(#" %# = %#",[sortedKeys objectAtIndex:s],[sortedValues objectAtIndex:s]);
}
You can try this to sort your Dictionary.
NSMutableDictionary *tmpDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"6",#"A",#"3",#"B",#"5",#"C",#"2",#"D",#"21",#"F",#"20",#"G",nil];
NSArray *sortedArray = [tmpDict keysSortedByValueUsingComparator:^NSComparisonResult(id obj1,id obj2){
return [obj1 compare:obj2 options:NSNumericSearch];
}];
NSLog(#"Sorted = %#",sortedArray);
NSDictionaryas well as NSMutableDictionary cannot be sorted by value. You can only use a NSArray to sort them. But you have to this with your own code and you won't get the same output as you want.
This is the simplest way to do this
NSArray *arr = [NSArray arrayWithObjects:#"2", #"4", #"1", nil];
NSArray *sorted = [arr sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"Pre sort : %#", arr);
NSLog(#"After sort : %#", sorted);
If you have f.ex. array of dictionary (or model objects), you could do this :
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:#"Mannie" forKey:#"name"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:#"Zannie" forKey:#"name"];
NSDictionary *dict3 = [NSDictionary dictionaryWithObject:#"Cannie" forKey:#"name"];
NSArray *peopleIKnow = [NSArray arrayWithObjects:dict1, dict2, dict3, nil];
NSSortDescriptor *sorty = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
NSArray *results = [peopleIKnow sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorty]];
NSLog(#"Before : %#", peopleIKnow);
NSLog(#"After : %#", results);

how to sort an NSArray of float values?

I have an NSArray like this:
how to sort NSarray float with value like this:122.00,45.00,21.01,5.90
#Ron's answer is perfect, but I want to add sorting by using an comparator block. For this trivial case it might be overkill, but it is very handy when it comes to sorting of objects in respect to several properties
NSArray *myArray =[NSArray arrayWithObjects: [NSNumber numberWithFloat:45.0],[NSNumber numberWithFloat:122.0], [NSNumber numberWithFloat:21.01], [NSNumber numberWithFloat:5.9], nil];
NSArray *sortedArray = [myArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 floatValue] > [obj2 floatValue])
return NSOrderedDescending;
else if ([obj1 floatValue] < [obj2 floatValue])
return NSOrderedAscending;
return NSOrderedSame;
}];
try this it work for me
NSArray *array=[[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:12.01],[NSNumber numberWithFloat:13.01],[NSNumber numberWithFloat:10.01],[NSNumber numberWithFloat:2.01],[NSNumber numberWithFloat:1.5],nil];
NSArray *sorted = [array sortedArrayUsingSelector:#selector(compare:)];
Here... use NSSortDescriptor
First Convert the float values into NSNumber
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"floatValue"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];
Hope it helps :)

Crazy array sorting in tableView! sortedArrayUsingSelector help?

My tableView app loads the data into the table view.
Everything works perfectly, but the array sorting is kind of messed, like you can see in the picture below. I thought about using the sortedArrayUsingSelector, to straighten things up, but I'm not sure which "sorting method" I should use.
How can I sort this so the cells are sorted according the numbers? Like the order would be 1. 2. 3. 4. 5. etc NOT 1. 10. 11. 12. 13. 14. 2. 3. ?
Thanks a lot in advance!!
And a two-liner:
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES comparator:^(id obj1, id obj2) { return [obj1 compare:obj2 options:NSNumericSearch]; }];
rowTitleArray = [rowTitleArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
Sorry for this convoluted approach, but this does work...
NSArray *rowTitleArray = [[NSArray alloc] initWithObjects:
#"10. Tenth",
#"15. Fifteenth",
#"13. Thirteenth",
#"1. First",
#"2. Second",
#"22. TwentySecond", nil];
NSMutableArray *dictionaryArray = [NSMutableArray array];
for (NSString *original in rowTitleArray) {
NSString *numberString = [[original componentsSeparatedByString:#"."] objectAtIndex:0];
NSNumber *number = [NSNumber numberWithInt:[numberString intValue]];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
number, #"number", original, #"rowTitle", nil];
[dictionaryArray addObject:dict];
}
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"number" ascending:YES];
NSArray *sortedDictionaryArray = [dictionaryArray sortedArrayUsingDescriptors:
[NSArray arrayWithObject:descriptor]];
NSMutableArray *sortedRowTitles = [NSMutableArray array];
for (NSDictionary *dict in sortedDictionaryArray) {
[sortedRowTitles addObject:[dict objectForKey:#"rowTitle"]];
}
rowTitleArray = [NSArray arrayWithArray:sortedRowTitles];
NSLog(#"%#", rowTitleArray);
Output:
"1. First",
"2. Second",
"10. Tenth",
"13. Thirteenth",
"15. Fifteenth",
"22. TwentySecond"
I will try to think of a more elegant solution.
Here is a more elegant solution:
NSInteger intSort(id num1, id num2, void *context) {
NSString *n1 = (NSString *) num1;
NSString *n2 = (NSString *) num2;
n1 = [[n1 componentsSeparatedByString:#"."] objectAtIndex:0];
n2 = [[n2 componentsSeparatedByString:#"."] objectAtIndex:0];
if ([n1 intValue] < [n2 intValue]) {
return NSOrderedAscending;
}
else if ([n1 intValue] > [n2 intValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
rowTitleArray = [rowTitleArray sortedArrayUsingFunction:intSort context:NULL];

Objective-c Sort Key array within array

Assuming I have an NSMutableArray which is loaded from file:
searchTermsArray = [[NSMutableArray alloc] initWithContentsOfFile: yourArrayFileName];
inside this array items are key objects
for (int i=0; i<[searchTermsArray count]; i++) {
NSLog(#"for array item %d: %# - %#",i,[[searchTermsArray objectAtIndex:i] objectForKey:#"title"], [[searchTermsArray objectAtIndex:i] objectForKey:#"theCount"] );
}
(which means that each array element (item) has 2 keys values:
searchTermsArray[0] = title (string) , theCount (also a string, but made out of integers)
Question: how should I sort "searchTermsArray" array from higher to lower based on "theCount" value?
(I am looking at the following code but it is not fitting the structure/syntax)
NSSortDescriptor *Sorter = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:NO];
[searchTermsArray sortUsingDescriptors:[NSArray arrayWithObject:Sorter]];
[Sorter release];
Shouldn't you be sorting based on theCount key?
NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:#"theCount" ascending:NO];
[searchTermsArray sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
I am not sure if there is a better way to do so. But this thing works.
NSInteger intSort(id param1, id param2, void *context) {
NSDictionary *dict1 = (NSDictionary *)param1;
NSDictionary *dict2 = (NSDictionary *)param2;
NSInteger dict1KeyCount = [[dict1 objectForKey:#"count"] intValue];
NSInteger dict2KeyCount = [[dict2 objectForKey:#"count"] intValue];
if (dict1KeyCount < dict2KeyCount) {
return NSOrderedAscending;
}else if (dict1KeyCount > dict2KeyCount) {
return NSOrderedDescending;
}else {
return NSOrderedSame;
}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:#"two", #"title", #"2", #"count", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"three", #"title", #"3", #"count", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"one", #"title", #"1", #"count", nil], nil];
NSArray *sortedArray = [array sortedArrayUsingFunction:intSort context:NULL];
for (NSDictionary *dict in sortedArray) {
NSLog(#"%d", [[dict objectForKey:#"count"] intValue]);
}
[super viewDidLoad];
}
The NSSortDescriptor is usually used to sort objects of a class. You pass the name of the property in that class to be compared with others.
Since what you have in your array actually seems to be a NSDictionary, the NSSortDescriptor might not be the best way to approach this problem. Besides, your objects in the dictionary must have a type, so I would try to sort the array myself in one of the classic methods if I were you.