1

我有一个 NSArray 对象(不是 NSStrings,而是自定义对象)。每个对象都有一个值obj.name ,我知道如何按名称对 NSMutableArray 进行排序,如下所示

 NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
 [array sortUsingDescriptors:[NSArray arrayWithObject:sort]];

但是,有些名称以“The”、“A”或“An”开头,如果它们出现,我想跳到名称中的下一个单词。有没有办法避免这三种情况并在出现时自动转移到下一个单词?

4

4 回答 4

5

如果我敢与迄今为止发布的所有答案相反,那么对您的文字问题的最简单答案是在您的自定义类上实现一个 getter,该类返回调整后的字符串:

- (NSString *)canonicalName
{
    if([self.name rangeOfString:@"The "].location == 0)
        return [self.name subStringFromIndex:4];

    // etc, etc
}

然后通过将“canonicalName”指定给排序描述符进行排序。

However, you should first consider following the advice in QA1159 and just using NSString's inherent ability to order itself as per the same rules applied by the Finder, which I think supersets the rules you're trying to implement. So you want to end up comparing strings via localizedCompare:, which has been available on iOS since the beginning. You're otherwise pretty much reinventing a non-trivial wheel.

E.g.

[array sortUsingComparator:
    ^NSComparisonResult(YourObjectType *obj1, YourObjectType *obj2)
    {
         return [obj1.name localizedCompare:obj2.name];
    }];
于 2013-01-25T23:27:09.433 回答
3

我建议执行“sortUsingSelector”,这将允许您编写自己的排序方法。然后,您将能够对这些条件进行三项检查,然后返回比较的两个字符串。

于 2013-01-25T22:54:49.693 回答
1

您可以使用sortedArrayUsingSelector. 查看NSArray 类参考

于 2013-01-25T22:56:38.093 回答
1

你必须实现自己的比较函数,像这样(它很粗糙,可以做得更优雅,但只是作为概念证明):

static NSInteger myCompare(NSString *obj1, NSString *obj2, void *context)
{
  NSString *str1;
  if ([obj1 hasPrefix:@"A "]) str1 = [obj1 substringFromIndex:2];
  else if ([obj1 hasPrefix:@"An "]) str1 = [obj1 substringFromIndex:3];
  else if ([obj1 hasPrefix:@"The "]) str1 = [obj1 substringFromIndex:4];
  else str1 = obj1;

  NSString *str2;
  if ([obj2 hasPrefix:@"A "]) str2 = [obj2 substringFromIndex:2];
  else if ([obj2 hasPrefix:@"An "]) str2 = [obj2 substringFromIndex:3];
  else if ([obj2 hasPrefix:@"The "]) str2 = [obj2 substringFromIndex:4];
  else str2 = obj2;

  return [str1 compare:str2];
}

然后你调用sortedArrayUsingFunction它:

sortedArray = [array sortedArrayUsingFunction:myCompare context:NULL];
于 2013-01-25T23:00:22.947 回答