我有一个名为allItems
的NSMutableArray,它有以下ProductData
个对象。
每个对象都有cid, cname, ctype
和cimage
。如下所示,json对象没有按顺序排列。但是,cid
是订购的指标。
我想知道你是如何根据cid订购的?
[
{
"cid": "2",
"cname": "Meats",
"ctype": "main",
"cimage": "baked_chicken.jpg"
},
{
"cid": "1",
"cname": "Dips",
"ctype": "side",
"cimage": "stuffed_eggplant.jpg"
},
{
"cid": "4",
"cname": "Sandwiches",
"ctype": "sand",
"cimage": "chickenshawarma.jpg"
},
{
"cid": "3",
"cname": "Appetizers",
"ctype": "side",
"cimage": "rice_lentils.jpg"
},
{
"cid": "5",
"cname": "Desserts",
"ctype": "dsrt",
"cimage": "cake.jpg"
}]
如果我使用sortDescriptior
,则部分有效。我面临的问题,在排序时,首先显示cid
1然后cid
10然后cid
2。
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"cid" ascending:YES];
[allItems sortUsingDescriptors:@[sortDescriptor]];
答案 0 :(得分:7)
使用带有比较器的排序描述符compare:options:
和选项NSNumericSearch
:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"cid" ascending:YES comparator:^(id obj1, id obj2) {
return [obj1 compare:obj2 options:NSNumericSearch];
}];
甚至更简单:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"cid" ascending:YES selector:@selector(localizedStandardCompare:)];
localizedStandardCompare
是一个特殊的比较选择器:
只要文件名或其他字符串出现在适合类似Finder的排序的列表和表中,就应该使用此方法。在不同的语言环境下,此方法的确切排序行为是不同的,并且可能在将来的版本中进行更改。此方法使用当前区域设置。
答案 1 :(得分:1)
使用此
NSSortDescriptor *aSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"cid" ascending:YES comparator:^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
sortedArray = [NSMutableArray arrayWithArray:[unsortedArray sortedArrayUsingDescriptors:@[aSortDescriptor]]];
答案 2 :(得分:1)
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"cId"
ascending:YES selector:@selector(caseInsensitiveCompare:)];
arrToBeSort = [arrToBeSort sortedArrayUsingDescriptors:[NSArray
descriptor]];
这将起作用
答案 3 :(得分:0)
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"cid.intValue" ascending:YES];
[array sortUsingDescriptors:@[sortDescriptor]];
您的“数组”现已在打印后进行排序
打印数组描述:&lt; __ NSArrayM 0x618000041bf0&gt;({cid = 1; cimage =“stuffed_eggplant.jpg”; cname = Dips; ctype = side;},{cid = 2; cimage =“baked_chicken.jpg”; cname = Meats; ctype = main;},{cid = 3; cimage =“rice_lentils.jpg”; cname =开胃菜; ctype = side;},{cid = 4; cimage =“chickenshawarma.jpg”; cname =三明治; ctype = sand;},{cid = 5; cimage =“cake.jpg”; cname = Desserts; ctype = dsrt;})