how to convert a dictionary's keys into an array sorted by the values to which those keys correspond in the dictionary

StackOverflow https://stackoverflow.com/questions/23303986

Domanda

I have a dictionary. Its keys are strings and its values are NSDates. For example:

{ A : <jan 1>, B : <mar 1>, C : <feb 1> }

I want to create an array from the keys in the dictionary (A, B, & C), sorted by date. So I should end up with the following array:

[A, C, B]

How can I accomplish this?

Bonus points: With that sorted array, I could accomplish my end goal, but the sorted array would be just an intermediary; the most elegant solution wouldn't need it. What I really want to do is sort an array of objects, each of which has a property value corresponding to one of the keys in the dictionary. For example:

[obj1, obj2, obj3]

where

obj1.prop = A
obj2.prop = B
obj3.prop = C

I want to sort that array based on the date values of A, B, & C, referencing the dictionary. So my end goal in this scenario would be the following array:

[obj1, obj3, obj2]

Thanks!

È stato utile?

Soluzione

Building on David's answer, this will solve it all together:

NSDictionary* items = @{ @"A":date1, @"B":date2, @"C":date3 };
NSArray *objectsArray = @{ obj1, obj2, obj3 };
NSArray *sortedObjectsArray = [objectsArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDate *date1 = [items objectForKey:obj1.prop];
    NSDate *date2 = [items objectForKey:obj2.prop];
    return [date1 compare:date2];
}];

Altri suggerimenti

The following will accomplish your first objective:

NSDictionary*   items = @{ @"A":@2, @"B":@1, @"C":@3};
keys = [[items allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [items[obj1] compare:items[obj2]];
}];

From that you should be able to extrapolate the answer to your other questions.

This should accomplish your second question

NSSortDescriptor *sortDescrip = [[NSSortDescriptor alloc] initWithKey:@"prop"
                                              ascending:YES];
NSArray *sortDescrips = [NSArray arrayWithObject:sortDescrip];
NSArray *sortedArray = [originalArray sortedArrayUsingDescriptors:sortDescrips];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top