Reputation: 1335
I'm new to iOS development, and I'm in problem that I don't know how to solve it...
I have JSON:
{
"038b7af5-2874-448b-88c3-f667908723d8" = {
Name = "Coffee";
Quantity = 5;
};
"4d63daaf-962b-4382-a90e-dd4db0ce052e" = {
Name = "Water";
Quantity = 1;
};
"693a6897-4250-4eef-8164-3bb1812315fc" = {
Name = "Fruit frappe";
Quantity = 1;
};
"778a66df-a2ec-419f-b9dc-94e0c0fef40d" = {
Name = "Fruit nes frappe";
Quantity = 1;
};
}
What I want to do is to sort them in UITableViewController
by quantity. I tried NSSortDescriptor
but with no success...
Thanks in advance,
Stefan
Upvotes: 1
Views: 127
Reputation: 9721
Dictionaries are unordered collection types.
To order the tableview you need to use an additional array (which can be ordered) of the dictionary keys.
So to populate item 0
of the tableview you get the key from the array at index 0
and then get the column values from the dictionary entry with that key.
In order to sort this array by Quanitity
you do this:
@property (readonly) NSMutableArray *arrayIndex;
@property (readonly) NSMutableDictionary *dataDict;
...
[arrayIndex sortUsingComparator:^NSComparisonResult(NSString *keyA, NSString *keyB) {
NSDictionary *dictA = _dataDict[keyA];
NSNumber *quantityA = dictA["Quantity"];
NSDictionary *dictB = _dataDict[keyB];
NSNumber *quantityB = dictB["Quantity"];
if (quantityA.integerValue > quantityB.integerValue)
return NSOrderedDescending;
else if (quantityA.integerValue < quantityB.integerValue)
return NSOrderedAscending;
return NSOrderedSame;
}];
Free tip: Don't store data in dictionaries if you can avoid it; instead convert the dictionary to a custom object as soon as possible as custom objects bring so much power and flexibility to your code, and look how much code I had to write just to make a comparator.
Upvotes: 3