csdnceshi67
bug^君
采纳率25%
2009-08-29 11:16

如何按字母顺序排序 NSArray?

已采纳

How can I sort an array filled with [UIFont familyNames] into alphabetical order?

转载于:https://stackoverflow.com/questions/1351182/how-to-sort-a-nsarray-alphabetically

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

7条回答

  • csdnceshi51 旧行李 12年前

    The simplest approach is, to provide a sort selector (Apple's documentation for details)

    Objective-C

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

    Swift

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

    Apple provides several selectors for alphabetic sorting:

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

    Swift

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

    Reference

    点赞 23 评论 复制链接分享
  • csdnceshi62 csdnceshi62 9年前

    The other answers provided here mention using @selector(localizedCaseInsensitiveCompare:) This works great for an array of NSString, however if you want to extend this to another type of object, and sort those objects according to a 'name' property, you should do this instead:

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

    Your objects will be sorted according to the name property of those objects.

    If you want the sorting to be case insensitive, you would need to set the descriptor like this

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
    
    点赞 28 评论 复制链接分享
  • weixin_41568134 MAO-EYE 8年前

    A more powerful way of sorting a list of NSString to use things like NSNumericSearch :

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

    Combined with SortDescriptor, that would give something like :

    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]];
    
    点赞 9 评论 复制链接分享
  • csdnceshi52 妄徒之命 6年前

    Another easy method to sort an array of strings consists by using the NSString description property this way:

    NSSortDescriptor *valueDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
    arrayOfSortedStrings = [arrayOfNotSortedStrings sortedArrayUsingDescriptors:@[valueDescriptor]];
    
    点赞 9 评论 复制链接分享
  • csdnceshi73 喵-见缝插针 6年前
    -(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];
        }
    
    点赞 4 评论 复制链接分享
  • csdnceshi62 csdnceshi62 6年前

    Use below code for sorting in alphabetical order:

        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);
    

    Below is console log :

    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
    )
    
    点赞 3 评论 复制链接分享
  • weixin_41568131 10.24 4年前

    This already has good answers for most purposes, but I'll add mine which is more specific.

    In English, normally when we alphabetise, we ignore the word "the" at the beginning of a phrase. So "The United States" would be ordered under "U" and not "T".

    This does that for you.

    It would probably be best to put these in categories.

    // 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;
    }
    
    点赞 评论 复制链接分享

相关推荐