Objective C - Sort an array of string

后端 未结 3 1415
长发绾君心
长发绾君心 2021-01-03 22:43

I have to sort an array of objects by a property of the objects that is a string. How can I do this?

相关标签:
3条回答
  • 2021-01-03 23:03

    For just sorting array of strings:

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

    For sorting objects with key "name":

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

    Also, instead of compare: you can use:

    • caseInsensitiveCompare:

    • localizedCaseInsensitiveCompare:

    0 讨论(0)
  • 2021-01-03 23:13

    you need to use

    -[NSArray sortedArrayUsingSelector:]
    

    or

    -[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter.

    here's a link to the answer Sort NSArray of date strings or objects

    0 讨论(0)
  • 2021-01-03 23:18

    Here's what I ended up using - works like a charm:

    [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 is just a @protocol SelectableCategory <NSObject> defining the category with all its properties and elements.

    0 讨论(0)
提交回复
热议问题