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.
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]];
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With