iOS objective 按数量对字典排序
iOS objective sort dictionary by quantity
我是iOS开发的新手,遇到了不知道如何解决的问题...
我有 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;
};
}
我想做的是按数量在UITableViewController
中对它们进行排序。我尝试了 NSSortDescriptor
但没有成功...
提前致谢,
斯特凡
字典是无序集合类型。
要订购表视图,您需要使用字典键的附加数组(可以订购)。
因此,要填充表视图的项目 0
,您需要从索引 0
处的数组中获取键,然后使用该键从字典条目中获取列值。
为了按 Quanitity
对数组进行排序,您可以这样做:
@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;
}];
免费提示:如果可以避免,不要将数据存储在字典中;相反,尽快将字典转换为自定义对象,因为自定义对象为您的代码带来如此强大的功能和灵活性,看看我不得不编写多少代码来制作比较器。
我是iOS开发的新手,遇到了不知道如何解决的问题...
我有 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;
};
}
我想做的是按数量在UITableViewController
中对它们进行排序。我尝试了 NSSortDescriptor
但没有成功...
提前致谢,
斯特凡
字典是无序集合类型。
要订购表视图,您需要使用字典键的附加数组(可以订购)。
因此,要填充表视图的项目 0
,您需要从索引 0
处的数组中获取键,然后使用该键从字典条目中获取列值。
为了按 Quanitity
对数组进行排序,您可以这样做:
@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;
}];
免费提示:如果可以避免,不要将数据存储在字典中;相反,尽快将字典转换为自定义对象,因为自定义对象为您的代码带来如此强大的功能和灵活性,看看我不得不编写多少代码来制作比较器。