【问题标题】:How to sort a NSArray alphabetically?如何按字母顺序对 NSArray 进行排序?
【发布时间】:2010-11-23 23:37:16
【问题描述】:

如何将填充有[UIFont familyNames] 的数组按字母顺序排序?

【问题讨论】:

    标签: objective-c sorting


    【解决方案1】:

    最简单的方法是,提供一个排序选择器(Apple's documentation 了解详情)

    Objective-C

    sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    

    斯威夫特

    let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:")
    let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor])
    

    Apple 提供了几个用于字母排序的选择器:

    • compare:
    • caseInsensitiveCompare:
    • localizedCompare:
    • localizedCaseInsensitiveCompare:
    • localizedStandardCompare:

    斯威夫特

    var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
    students.sort()
    print(students)
    // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
    

    Reference

    【讨论】:

    • 文档链接已过时,代码示例不足以对数组进行实际排序。 localCaseInsensitiveCompare:需要以某种方式定义。
    • 我更新了链接。感谢您指出了这一点。 localCaseInsensitiveCompare:是 NSString 的一个方法,应该足以对字符串数组进行排序。
    • 这可以很容易地应用于包含任何自定义对象(不仅仅是 NSString)的数组。您只需确保数组中的所有对象都实现了选择器指定的消息。然后在此消息中,您只需为要比较的对象的属性调用 NSString 比较。
    • 这么简单的事情一定不要这么复杂。
    【解决方案2】:

    此处提供的其他答案提到使用@selector(localizedCaseInsensitiveCompare:) 这对于 NSString 数组非常有用,但是如果您想将其扩展到另一种类型的对象,并根据“名称”属性对这些对象进行排序,则应该这样做:

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]];
    

    您的对象将根据这些对象的名称属性进行排序。

    如果您希望排序不区分大小写,则需要像这样设置描述符

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
    

    【讨论】:

    • +1,谢谢。有趣的是,这是比公认的答案更常见的用例。
    • 先对大写字母排序,再对小写字母排序
    • +1,排序描述符和选择器正是我想要的,没有其他答案有这个。非常感谢人
    • 当我尝试以这种方式对字符串数组进行排序时出现错误,因为name 不是有效的键。使用 NSSortDescriptor 按字母顺序对字符串进行排序时,我使用什么键?
    【解决方案3】:

    一种更强大的排序 NSString 列表以使用 NSNumericSearch 之类的方法:

    NSArray *sortedArrayOfString = [arrayOfString sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
            }];
    

    与 SortDescriptor 结合,会给出类似的结果:

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
            return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
        }];
    NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
    

    【讨论】:

      【解决方案4】:

      另一种对字符串数组进行排序的简单方法是通过这种方式使用 NSString description 属性:

      NSSortDescriptor *valueDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
      arrayOfSortedStrings = [arrayOfNotSortedStrings sortedArrayUsingDescriptors:@[valueDescriptor]];
      

      【讨论】:

      • 好像有点没用;没有理由以这种方式对字符串进行排序(这样做可能会影响性能),并且对于其他对象,它的 description 属性很少用于排序目的。
      【解决方案5】:

      使用以下代码按字母顺序排序:

          NSArray *unsortedStrings = @[@"Verdana", @"MS San Serif", @"Times New Roman",@"Chalkduster",@"Impact"];
      
          NSArray *sortedStrings =
          [unsortedStrings sortedArrayUsingSelector:@selector(compare:)];
      
          NSLog(@"Unsorted Array : %@",unsortedStrings);        
          NSLog(@"Sorted Array : %@",sortedStrings);
      

      以下是控制台日志:

      2015-04-02 16:17:50.614 ToDoList[2133:100512] Unsorted Array : (
          Verdana,
          "MS San Serif",
          "Times New Roman",
          Chalkduster,
          Impact
      )
      
      2015-04-02 16:17:50.615 ToDoList[2133:100512] Sorted Array : (
          Chalkduster,
          Impact,
          "MS San Serif",
          "Times New Roman",
          Verdana
      )
      

      【讨论】:

        【解决方案6】:

        这已经为大多数目的提供了很好的答案,但我会添加我的更具体的答案。

        在英语中,通常当我们按字母顺序排列时,我们会忽略短语开头的“the”这个词。所以“美国”将在“U”而不是“T”下排序。

        这会为你做到这一点。

        最好将这些分类。

        // Sort an array of NSStrings alphabetically, ignoring the word "the" at the beginning of a string.
        
        -(NSArray*) sortArrayAlphabeticallyIgnoringThes:(NSArray*) unsortedArray {
        
            NSArray * sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) {
        
                //find the strings that will actually be compared for alphabetical ordering
                NSString* firstStringToCompare = [self stringByRemovingPrecedingThe:a];
                NSString* secondStringToCompare = [self stringByRemovingPrecedingThe:b];
        
                return [firstStringToCompare compare:secondStringToCompare];
            }];
            return sortedArray;
        }
        
        // Remove "the"s, also removes preceding white spaces that are left as a result. Assumes no preceding whitespaces to start with. nb: Trailing white spaces will be deleted too.
        
        -(NSString*) stringByRemovingPrecedingThe:(NSString*) originalString {
            NSString* result;
            if ([[originalString substringToIndex:3].lowercaseString isEqualToString:@"the"]) {
                result = [[originalString substringFromIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            }
            else {
                result = originalString;
            }
            return result;
        }
        

        【讨论】:

        • 几年后我才看这个,我意识到它也应该包括“a”和“an”。这些应该很容易添加。
        【解决方案7】:
        -(IBAction)SegmentbtnCLK:(id)sender
        { [self sortArryofDictionary];
            [self.objtable reloadData];}
        -(void)sortArryofDictionary
        { NSSortDescriptor *sorter;
            switch (sortcontrol.selectedSegmentIndex)
            {case 0:
                    sorter=[[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES];
                    break;
                case 1:
                    sorter=[[NSSortDescriptor alloc]initWithKey:@"Age" ascending:YES];
                    default:
                    break; }
            NSArray *sortdiscriptor=[[NSArray alloc]initWithObjects:sorter, nil];
            [arr sortUsingDescriptors:sortdiscriptor];
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多