【问题标题】:Objective C - Sort an array of stringObjective C - 对字符串数组进行排序
【发布时间】:2011-08-14 19:50:01
【问题描述】:

我必须按对象的属性(即字符串)对对象数组进行排序。 我该怎么做?

【问题讨论】:

    标签: objective-c arrays string sorting


    【解决方案1】:

    你需要使用

    -[NSArray sortedArrayUsingSelector:]
    

    -[NSMutableArray sortUsingSelector:] 并将@selector(compare:) 作为参数传递。

    这是答案的链接 Sort NSArray of date strings or objects

    【讨论】:

      【解决方案2】:

      仅对字符串数组进行排序:

      sorted = [array sortedArrayUsingSelector:@selector(compare:)];
      

      使用键“name”对对象进行排序:

      NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)];
      sorted = [array sortedArrayUsingDescriptors:@[sort]];
      

      另外,您可以使用 compare: 代替:

      • caseInsensitiveCompare:

      • localizedCaseInsensitiveCompare:

      【讨论】:

        【解决方案3】:

        这是我最终使用的 - 就像一个魅力:

        [categoryArray sortedArrayWithOptions:0
                       usingComparator:^NSComparisonResult(id obj1, id obj2)
        {
            id<SelectableCategory> cat1 = obj1;
            id<SelectableCategory> cat2 = obj2;
            return [cat1.name compare:cat2.name options:NSCaseInsensitiveSearch];
        }];
        

        SelectableCategory 只是一个 @protocol SelectableCategory &lt;NSObject&gt; 定义了包含其所有属性和元素的类别。

        【讨论】:

          猜你喜欢
          • 2013-04-04
          • 2012-08-31
          • 2014-08-11
          • 1970-01-01
          • 2012-09-13
          • 2013-09-22
          • 1970-01-01
          • 2016-07-18
          相关资源
          最近更新 更多