代码之家  ›  专栏  ›  技术社区  ›  iOSPawan

如何对包含nsdictionary的nsarray进行排序?

  •  1
  • iOSPawan  · 技术社区  · 16 年前

    我有一个 NSArray 其中包含 NSDictionary 物体。每一个 字典 对象包含 ORDER 关键。

    这个我怎么分类 不可变数组 基于每个键中的这个键 NSDictionaries ?

    3 回复  |  直到 10 年前
        1
  •  7
  •   Niko    16 年前

    下面是一个例子。想象你有一系列的词汇。ecah dictionary有两个键“name”和“dateofbirth”。您可以按“名称”对数组进行排序,如下所示:

    //
    // Sort array by name
    //
    NSSortDescriptor *Sorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    [myArray sortUsingDescriptors:[NSArray arrayWithObject:Sorter]];
    [Sorter release];
    

    注意 myArray 是一个 NSMutableArray .

        2
  •  4
  •   Alex Reynolds    16 年前

    阅读 Sorting with Sort Descriptors 苹果部分 Collections Programming Topics .

    本节中的示例包括按字典对象的键对其数组进行排序。

        3
  •  1
  •   Bankim    10 年前

    对字典数组排序 你必须使用 NSSortDescriptor 这样,您就可以根据键对字典数组进行排序。

    在这里输入代码,通过 NSMutableArray 使用要排序的dict对象

    -(NSMutableArray*)sortingArrayOfDict:(NSMutableArray *)arrayTosort sortByObject:(NSString*)sortKey{
    NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:YES];
    [arrayTosort sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];
    return arrayTosort;
     }
    

    或者甚至可以通过设置“是/否”按升序或降序对其进行排序。

    推荐文章