Objective-c Sort Key array within array - iphone

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.

Related

How to compare two MutableArrays and display the unmatched value in iphone? [duplicate]

This question already has answers here:
Compare 2 nsmutablearray and get different object to third array in ios
(4 answers)
Closed 9 years ago.
I have two MutableArray values like.
NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:#"Apple", #"Orange", #"Grapes", #"Banana", nil];
NSMutableArray *array1=[[NSMutableArray alloc]initWithObjects:#"Apple", #"Orange", #"Grapes", nil];
Now i have to compare that two Mutable arrays and display that unmatched object "Banana" into one string.
I am fresher to iOS so, anybody would send me the code for that problem.
Thanks in Advance.
As others have suggest, NSSet is probably your best bet. However, given that *array is mutable, you could simply remove the objects from it contained in *array1
NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:#"Apple", #"Orange", #"Grapes", #"Banana", nil];
NSMutableArray *array1=[[NSMutableArray alloc]initWithObjects:#"Apple", #"Orange", #"Grapes", nil];
[array removeObjectsInArray:array1];
NSLog(#"array: %#", array); // array: ( Banana )
// if you require result as a string
NSString *objectsAsString = [array componentsJoinedByString:#", "];
NSLog(#"objects as string: %#", objectsAsString); // objects as string: Banana
for(int i=0;i<[array count];i++)
{
NSString *str1 = [array objectAtIndex:i];
for(int j=0;j<[array1 count];j++)
{
NSString *str2 = [array1 objectAtIndex:j];
if([str1 isEqualToString:str2])
{
//do something which you want i.e add the values to some other array
}
}
}
You should probably use NSSet for this purpose
NSSet *set1 = [NSSet setWithObjects:#"a", #"s", #"d", #"f", nil];
NSSet *set2 = [NSSet setWithObjects:#"a", #"s", nil];
NSMutableSet *notInSet1 = [NSMutableSet setWithSet:set2];
[notInSet1 minusSet:set1];
NSMutableSet *notInSet2 = [NSMutableSet setWithSet:set1];
[notInSet2 minusSet:set2];
NSMutableSet *symmetricDifference = [NSMutableSet setWithSet:notInSet1];
[symmetricDifference unionSet:notInSet2];
NSArray *array1 = [[NSArray alloc] initWithObjects:#"a",#"b",#"c",nil];
NSArray *array2 = [[NSArray alloc] initWithObjects:#"a",#"d",#"c",nil];
NSMutableArray *ary_result = [[NSMutableArray alloc] init];
NSMutableArray *ary_resultUnmatched = [[NSMutableArray alloc] init];
for(int i = 0;i<[array1 count];i++)
{
for(int j= 0;j<[array2 count];j++)
{
if([[array1 objectAtIndex:i] isEqualToString:[array2 objectAtIndex:j]])
{
[ary_result addObject:[array1 objectAtIndex:i]];
} else {
[ary_resultUnmatched addObject:[array1 objectAtIndex:i]];
}
}
}
NSLog(#"%#",ary_result);//it will print a,c
NSLog(#"%#",ary_resultUnmatched);//it will print b,d
so in else condition you'll have your un matched values

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 :)

returning 8 closest cgfloat from a table lookup based on a cgfloat

I am trying to create this method. Let's call this
-(NSMutableArray*) getEightClosestSwatchesFor:(CGFloat)hue
{
NSString *myFile = [[NSBundle mainBundle] pathForResource:#"festival101" ofType:#"plist"];
NSMutableArray* myArray = [NSArray arrayWithContentsOfFile:myFile];
for (NSDictionary *dict in myArray)
{
NSLog(#"[plistData valueForKey:aKey] string] is %f", [[dict valueForKey:#"hue"] floatValue]) ;
}
return myArray;
}
pretty much, I am passing a cgfloat to this method which then needs to check a plist file which have hue key for 100 elements. I need to compare my hue with all of the hues and get 8 most closest hue and finally wrap these into an array and return this.
What would be most efficient way of doing this? Thanks in advance.
Here's my method if anyone is interested. Feel free to comment on it.
-(NSArray*)eightClosestSwatchesForHue:(CGFloat)hue
{
NSMutableArray *updatedArray = [[NSMutableArray alloc] initWithCapacity:100];
NSString *myFile = [[NSBundle mainBundle] pathForResource:#"festival101" ofType:#"plist"];
NSMutableArray* myArray = [NSArray arrayWithContentsOfFile:myFile];
for (NSDictionary *dict in myArray)
{
CGFloat differenceHue = fabs(hue - [[dict valueForKey:#"hue"] floatValue]);
//create a KVA for the differenceHue here and then add it to the dictionary and add this dictionary to the array.
NSDictionary* tempDict = [NSDictionary dictionaryWithObjectsAndKeys:
[dict valueForKey:#"id"], #"id",
[NSNumber numberWithFloat:differenceHue], #"differenceHue",
[dict valueForKey:#"color"], #"color",
nil];
[updatedArray addObject:tempDict];
}
//now we have an array of dictioneries with values we want. we need to sort this from little to big now.
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"differenceHue" ascending:YES];
[updatedArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
[descriptor release];
//now get the first 8 elements and get rid of the remaining.
NSArray *finalArray = [updatedArray subarrayWithRange:NSMakeRange(0,8)];
[updatedArray release];
return finalArray;
}

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];