根据一个属性sorting数组
我有一个名为allItems
具有以下ProductData
对象的NSMutableArray。
每个对象都有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
,它部分工作。 我面临的问题,当它sorting,它首先显示cid
1,然后cid
10,然后cid
2。
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"cid" ascending:YES]; [allItems sortUsingDescriptors:@[sortDescriptor]];
使用带比较器的sorting描述符传递compare:options:
和option 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
是一个特殊的比较select器:
只要文件名或其他string以列表和表格的forms出现在Findertypes的sorting适当的地方,就应该使用这种方法。 此方法的确切sorting行为在不同的语言环境下有所不同,并且在将来的版本中可能会更改。 此方法使用当前的语言环境。
用这个
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]]];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"cId" ascending:YES selector:@selector(caseInsensitiveCompare:)]; arrToBeSort = [arrToBeSort sortedArrayUsingDescriptors:[NSArray descriptor]];
这将工作
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"cid.intValue" ascending:YES]; [array sortUsingDescriptors:@[sortDescriptor]];
打印之后,您的“数组”已经被分类
打印数组的描述:<__ NSArrayM 0x618000041bf0>({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 = Appetizers; ctype = side;},{cid = 4; cimage =“chickenshawarma.jpg”; cname = Sandwiches; ctype = sand; },{cid = 5; cimage =“cake.jpg”; cname = Desserts; ctype = dsrt;})