NSMutableDictionary does not sort correctly - iphone

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

Related

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

Objects Sorting With date ,Time Problem in Array(Iphone Development)

I have Problem related to array Sorting.
I have an NSMutable array say's A.Which has an class object b on its each index.
class b contain's multiple field Like int,string and nsdate.
I want to sort the A array on the basis of class b time(NSdate) ascendingly.
I follow the date sorting question on stackoverflow but that's only for date array.
Sort NSArray of date strings or objects
Kindly guide me.
Thank's in advance
Here you go just modify some part of code for your requirement
- (NSArray *)sortedWeightEntriesByWeightDate:(NSArray *)unsortedArray {
NSMutableArray *tempArray = [NSMutableArray array];
NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:0];
#try {
for(int i = 0; i < [unsortedArray count];i++) {
NSDateFormatter *df = [[NSDateFormatter alloc]init];
MyDataModal *entry = [unsortedArray objectAtIndex:i];
[df setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [df dateFromString:entry.weightDate];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
if(date) {
[dict setObject:entry forKey:#"entity"];
[dict setObject:date forKey:#"date"];
[tempArray addObject:dict];
}
[df release];
}
NSInteger counter = [tempArray count];
NSDate *compareDate;
NSInteger index;
for(int i = 0 ; i < counter; i++) {
index = i;
compareDate = [[tempArray objectAtIndex:i] valueForKey:#"date"];
NSDate *compareDateSecond;
for(int j = i+1 ; j < counter; j++) {
compareDateSecond=[[tempArray objectAtIndex:j] valueForKey:#"date"];
NSComparisonResult result = [compareDate compare:compareDateSecond];
if(result == NSOrderedDescending) {
compareDate = compareDateSecond;
index=j;
}
}
if(i!=index)
[tempArray exchangeObjectAtIndex:i withObjectAtIndex:index];
}
NSInteger counterIndex = [tempArray count];
for(int i = 0; i < counterIndex ; i++) {
[sortedArray addObject:[[tempArray objectAtIndex:i] valueForKey:#"entity"]];
}
}
#catch (NSException * e) {
NSLog(#"An exception occured while sorting weight entries by date");
}
#finally {
return [NSArray arrayWithArray:sortedArray];
}
}
How about:
NSArray *myArray = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantFuture], #"theDate", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantPast], #"theDate", nil],
nil];
NSLog(#"Before sorting: %#", myArray);
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey: #"theDate" ascending: YES];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject: dateSortDescriptor]];
NSLog(#"After Sorting: %#", sortedArray);
This presumes that the date you want to sort for has a key (it is a property, essentially.)

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.

Help with a For loop and NSMutableDictionary

I am using a for loop to (currently) NSLog the contents of a NSArray. However I would like to set the contents of the array into a NSMutableDictionary, depending on the objectAtIndex it is. Currently there are 843 objects in the array, and therefore I would rather not have to type out the same thing over and over again!
My code currently is this
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
string = [string stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSArray *chunks = [string componentsSeparatedByString:#","];
for (int i = 0; i < [chunks count]; i ++) {
NSLog(#"%#", [chunks objectAtIndex:i]);
}
I would like to set the contents of the array into the NSMutableDictionary in the following fashion, and once the objectAtIndex is 11, I would like to set the 12th object in the dictionary to be of the key #"type" and soforth:
[dict setObject:[chunks objectAtIndex:0] forKey:#"type"];
[dict setObject:[chunks objectAtIndex:1] forKey:#"name"];
[dict setObject:[chunks objectAtIndex:2] forKey:#"street"];
[dict setObject:[chunks objectAtIndex:3] forKey:#"address1"];
[dict setObject:[chunks objectAtIndex:4] forKey:#"address2"];
[dict setObject:[chunks objectAtIndex:5] forKey:#"town"];
[dict setObject:[chunks objectAtIndex:6] forKey:#"county"];
[dict setObject:[chunks objectAtIndex:7] forKey:#"postcode"];
[dict setObject:[chunks objectAtIndex:8] forKey:#"number"];
[dict setObject:[chunks objectAtIndex:9] forKey:#"coffee club"];
[dict setObject:[chunks objectAtIndex:10] forKey:#"latitude"];
[dict setObject:[chunks objectAtIndex:11] forKey:#"longitude"];
I'm not sure I fully understand the question, but I think that your chunks array contains a long list of data, ordered in the same way (i.e. 0th, 12th, 24th, 36th... elements are all type, and 1st, 13th, 25th, 37th... elements are all name). If this is the case, you could use something like this:
NSArray *keys = [NSArray arrayWithObjects:#"type", #"name", #"street", #"address1", #"address2", #"town", #"county", #"postcode", #"number", #"coffee club", #"latitude", #"longitude", nil];
for (NSUInteger i = 0; i < [chunks count]; i += [keys count])
{
NSArray *subarray = [chunks subarrayWithRange:NSMakeRange(i, [keys count])];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:subarray forKeys:keys];
// do something with dict
[dict release];
}
Note that you can't have two different values for the same key with NSDictionary. That is, if you set two different values for the type key, only the last value set will be kept.
Edit
If your array is not a multiple of 12 because for example it contains garbage data at the end, you could use a different looping style instead:
// max should be a multiple of 12 (number of elements in keys array)
NSUInteger max = [chunks count] - ([chunks count] % [keys count]);
NSUInteger i = 0;
while (i < max)
{
NSArray *subarray = [chunks subarrayWithRange:NSMakeRange(i, [keys count])];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:subarray forKeys:keys];
// do something with dict
[dict release];
i += [keys count];
}
Since there's no pattern to your keys, you're better off doing it manually like you're doing it now.
The most straightforward thing to do would be to use the code you posted. But if you really want to use a loop, something like this should do.
NSArray *keys = [NSArray arrayWithObjects:#"type", #"name", #"street", #"address1", #"address2", #"town", #"county", #"postcode", #"number", #"coffee club", #"latitude", #"longitude", nil];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
string = [string stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSArray *chunks = [string componentsSeparatedByString:#","];
for (int i = 0; i < [chunks count] && i < [keys count]; i ++) {
[dict setObject:[chunks objectAtIndex:i] forKey:[keys objectAtIndex:i]];
}
NSArray* keys = [NSArray arrayWithObjects:#"type",#"name",#"street",#"address1",#"address2",#"town",#"county",#"postcode",#"number",#"coffee club",#"latitude",#"longitude",nil];
for (int i = 0; i < [chunks count]; i ++){
[dict setObject:[chucks objectAtIndex:i] forKey:[keys objectAtIndex:i]];
}