开发者

Objective C - Sort an array of string

开发者 https://www.devze.com 2023-03-01 03:27 出处:网络
I have to sort an array of objects by a property of the objects that is a string. How can I do this?开发者_如何学Cyou need to use

I have to sort an array of objects by a property of the objects that is a string. How can I do this?开发者_如何学C


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


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:


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

精彩评论

暂无评论...
验证码 换一张
取 消