Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting NSMutableArrays alphabetically

I have an NSMutableArray, called categories, which contains an object called CategoryItem. CategoryItem has an NSString property, *text. Now how would I sort this Array based on the text property of the elements? Sorry if this doesn't make sense, I'm new to all this.

I tried this:

[categories sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

But it failed.

like image 779
Mackey18 Avatar asked Nov 18 '25 01:11

Mackey18


2 Answers

That's because you're trying to sort the array based on each object, not on the string it contains.

You need to use an instance of NSSortDescriptor to sort your array. You can create one like this:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"text" ascending:YES];

Then:

[categories sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
like image 105
Extra Savoir-Faire Avatar answered Nov 20 '25 16:11

Extra Savoir-Faire


Try this:

[categories sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    CategoryItem object1 = (CategoryItem)obj1;
    CategoryItem object2 = (CategoryItem)obj2;
    return [object1.text compare:object2.text];
}];

Hope that helps!

like image 21
danielM Avatar answered Nov 20 '25 18:11

danielM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!