Mackey18
Mackey18

Reputation: 2352

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.

Upvotes: 2

Views: 4032

Answers (4)

Extra Savoir-Faire
Extra Savoir-Faire

Reputation: 6036

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]];

Upvotes: 10

danielM
danielM

Reputation: 2512

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!

Upvotes: 7

ColdLogic
ColdLogic

Reputation: 7265

You kinda did this right.

The problem being that you're trying to sort strings, but you dont have strings, you have CategoryItems. To keep the same code, you would just implement localizedCaseInsensitiveCompare: for CategoryItem. In that function, compare the text value and return the correct NSComparisonResult. Probably something like this

-(NSComparisonResult)localizedCaseInsensitiveCompare:(CategoryItem *)item2 {
    return [text localizedCaseInsensitiveCompare:[item2 text]];
}

Upvotes: 2

jimpic
jimpic

Reputation: 5520

It fails because you did not implement localizedCaseInsensitiveCompare for CategoryItem.

If you want to do that, implement that function for CategoryItem like

- (NSComparisonResult)localizedCaseInsensitiveCompare:(CategoryItem *)anItem
{
    return [anItem.stringProperty localizedCaseInsensitiveCompare:self.stringProperty];
}

Upvotes: 4

Related Questions