0

I have code as follows:

-(NSInteger) sortList:(NSMutableArray*)list {
    if(!list)
        return -1;

    //sort list
     [list sortUsingSelector:@selector(compare:)];

   //do other stuff

}

My code constantly crashes with *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI sortUsingSelector:]: unrecognized selector sent to instance

The list is not empty and definitely contains some elements. So I have no idea why it is crashing. I instead tried to use this piece of code instead for comparision

 [list sortUsingComparator:^NSComparisonResult(id  obj1, id obj2) {
            NSNumber *num1 = obj1;
            NSNumber *num2 = obj2;

        if([num1 integerValue] <= [num2 integerValue]){
                return NSOrderedAscending;
            } 
        else
            return NSOrderedDescending;
    }];

Also crashes with the same issue. Any idea what I might be doing wrong here?

4
  • 4
    That means that your array is in fact an immutable NSArray ... Commented Mar 29, 2017 at 18:50
  • Possible duplicate of stackoverflow.com/questions/22570144/…. Commented Mar 29, 2017 at 18:51
  • 1
    Your title doesn't match your question. Commented Mar 29, 2017 at 19:06
  • @MartinR Thanks for the tip. I had an array of arrays. The outer array was NSMutable but the internal one was NSArray type and I had failed to notice that. Thanks again! Commented Mar 30, 2017 at 5:14

1 Answer 1

1

This seems to work for me, but it doesn't sort inline, rather returns the sorted list:

-(NSArray *) sortList:(NSMutableArray*)list {

    NSMutableArray *copy = [list mutableCopy];

    [copy sortUsingComparator:^NSComparisonResult(id  _Nonnull num1, id  _Nonnull num2) {
            if([num1 integerValue] <= [num2 integerValue]){
                return NSOrderedAscending;
            }
            else
                return NSOrderedDescending;

    return copy;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Good idea to make the param mutable, but the OP ought to discover why the param she/he thinks is mutable sometimes isn't. Moreover, once you know that you have a mutable copy, respondsToSelector:@selector(sortUsingComparator:) is superfluous.
Also, the nil check is superfluous.
Why convert NSNumber into integer to do the compare, and not use directly compare:? return [num1 compare:num2] if OP still wants to use comparator?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.