I need to display in a UITableView the content of a NSDictionary returned by an API, respecting the order of the keys.
I'm using :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *key = self.data.allKeys[indexPath.section];
NSArray *list = self.data[key];
id data = list[indexPath.row];
PSSearchCell *cell = [PSSearchCell newCellOrReuse:tableView];
cell.model = data;
return cell;
}
but as I do self.data.allKeys
, I'm loosing the order of my keys. I can't sort them by value as it doesn't concern them.
As everyone said, I can't order my keys as they appear in my NSDictionary log because a NSDictionary is not ordered.
I asked people from the API to return an array instead:
/----------------------------------------------------------------------------/
Too bad there isn't a method "sortedArrayUsingArray" used like that :
Try this,
Now fetch values based on the key sorted.
EDIT
To sort them in alphabetical order try this,
I wrote a quick method to take a source array (of objects that are all out of order) and a reference array (that has objects in a desired (and totally arbitrary) order), and returns an array where the items of the source array have been reorganized to match the reference array.
Note that this is very fragile. It uses
NSArray
'scontainsObject:
method, which ultimately will callNSObject
'sisEqual:
. Basically, it should work great for arrays ofNSString
s,NSNumber
s, and maybeNSDate
s (haven't tried that one yet), but outside of that, YMMV. I imagine if you tried to pass arrays ofUITableViewCell
s or some other really complex object, it would totally sh*t itself, and either crash or return total garbage. Likewise if you were to do something like pass an array ofNSDate
s as the reference array and an array ofNSString
s as the source array. Also, if the source array contains items not covered in the reference array, they'll just get discarded. One could address some of these issues by adding a little extra code.All that said, if you're trying to do something simple, it should work nicely. In your case, you just send
arrayOne
from the answer you posted as the source array, andarrayTwo
as the reference array.You said that you were losing the order of the keys, so I suppose you pull those keys from a
NSArray
. Right? And in thatNSArray
you have the keys ordered as you want. And I also see that the objects of theNSDictionary
areArrays
, right? Yes. So in yourOrdered Array
you have more arrays.data
is the name of the NSDictionary.So, all you have to do is to bring that
NSArray
(the one that is ordered as you always wanted) into this .m file and after that use some awesome code in yourcellForRowAtIndexPath
method. You can do it by doing the following:And this is all you have to do to keep the order you want using a NSDictionary and NSArray.
To visualize it better, in the case that your ordered array only contains strings it would be like this:
Hope it helps.