Sorting NSArray which many contain number

后端 未结 3 612
日久生厌
日久生厌 2020-12-14 11:39

I have an NSArray which is populated with objects from an NSMutableArray. Most of these object have integer values like \"1\", \"2\", \"3\", \"4\", \"5\", sometimes there is

3条回答
  •  眼角桃花
    2020-12-14 11:57

    You can use NSArray's -sortedArrayUsingComparator: method to get a sorted array using a custom block. I find this more convenient than -sortedArrayUsingSelector:, because you can declare the comparator inline, like so:

    NSArray *unsortedArray = [NSArray arrayWithObjects:@"Hello", @"4", @"Hi", @"5", @"2", @"10", @"1", nil];
    NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
        return [str1 compare:str2 options:NSNumericSearch];
    }];
    

    This will return an array that looks like so:

    (
        1,
        2,
        4,
        5,
        10,
        Hello,
        Hi
    )
    

    In general, it's pretty nice to use blocks because they eliminate the need to create random selectors that run amuk in your code.

提交回复
热议问题