Error thrown when using sortingUsingDescriptors, NSSortDescriptor and sortDescriptorWithKey methods on an NSMutable array

StackOverflow https://stackoverflow.com/questions/21272128

Question

I created an array of objects, and one of the properties of the object is "rank". I want to sort the array by the rank value of each object in it.

It throws the following error:

-[NSSortDescriptor count]: unrecognized selector sent to instance 0x10a0537d0

Here's my method call on the array of objects:

[_objects sortUsingDescriptors:[NSSortDescriptor sortDescriptorWithKey:@"rank" ascending:YES selector:@selector(compare:)]];

And here's the relevant code from the class that the objects in the array belong to:

@synthesize rank;
- (void)initWithRank:(int)rankNum Name:(NSString*)nameString URL:(NSString*)urlString
{
    self.rank = [NSNumber numberWithInt:rankNum];
    self.name = nameString;
    self.url = urlString;
}

As you can see, "rank" is an NSNumber, and the NSNumber class has a method called "compare:" that's supposed to compare NSNumbers by their values, so I don't understand why it's telling me the selector is unrecognized. Thanks in advance for any help.

Was it helpful?

Solution

sortUsingDescriptors: expects an NSArray of sort descriptors as its first argument:

[_objects sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"rank" ascending:YES selector:@selector(compare:)]]];

Or a bit longer:

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"rank" ascending:YES selector:@selector(compare:)];
[_objects sortUsingDescriptors:@[descriptor]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top