2

我需要使用字典中的键控对象对字典数组进行排序(尽可能接近快速排序),但是由于我的字典的复杂性(键值的数量)和可以在其中返回的数据,我需要能够根据字典中的几个键值对每个字典进行排序。

例如,假设数组 [0]、数组 [1] 中的字典键值 1 是否相等,然后检查键值 2 是否相等,如果是,则继续向下键值列表直到您可以对数组 [0] 和 [ 进行排序的两项1] 上。

我已经阅读了 NSSortDescriptor 并指定了要与可以设置升序或降序的位置进行比较的属性,但我不确定这是否可以用来实现我想要实现的目标。

我已经得到了一个我需要做的例子,但它在 delphi 中,我不是很熟悉,但是我认为这个例子对我正在尝试做的事情提供了一些见解。

//
Result := AnsiCompareText (left.property1, right.Property1);
if Result <> 0 then Exit;
Result := AnsiCompareText (left.property2, right.Property2);
if Result <> 0 then Exit;
Result := AnsiCompareText (left.property3, right.Property3);
if Result <> 0 then Exit;
Result := AnsiCompareText (left.property4, right.Property4);
if Result <> 0 then Exit;
Result := AnsiCompareText (left.property5, right.Property5);
if Result <> 0 then Exit;
//

希望这会给您一些关于我想要实现的目标的想法,如果您知道目标 C 中的类似解决方案,我很乐意听到它的任何帮助!:P

4

1 回答 1

3

假设您有一个可变数组。然后你用这个:

[myArray sortUsingComparator:^ NSComparisonResult(NSDictionary *d1, NSDictionary *d2)
{
  // you have two items - use whatever complex logic you want, then return
  // one of NSOrderedAscending, NSOrderedSame, NSOrderedDescending
} ];

例如,假设您只关心一个“名称”属性:

[myArray sortUsingComparator:^ NSComparisonResult(NSDictionary *d1, NSDictionary *d2)
{
  NSString *n1 = [d1 objectForKey:@"name"];
  NSString *n2 = [d2 objectForKey:@"name"];
  return [n1 localizedCompare:n2];
} ];

这种技术的真正好处是逻辑可以任意复杂。

于 2012-08-07T00:44:37.217 回答