objective-cnsmutablearraycompare

Sorting objects in NSMutableArray with sortUsingComparator


I have the following mutable array:

NSMutableArray *persons = [[NSMutableArray alloc]initWithObjects:person1, person2, person3, nil];

where every person is an object, which contains (NSInteger) personAge and (NSString*) personName properties. Now I want to sort this array by personAge. So I tried the following:

[persons sortUsingComparator:
     ^NSComparisonResult(id obj1, id obj2)
     {
         Person *p1 = (Person*)obj1;
         Person *p2 = (Person*)obj2;

        return [p1.personAge compare: p2.personAge];

     }];

    NSLog(@"%ld", [persons componentsJoinedByString:@" "]);

But I'm getting a "Bad receiver type 'NSInteger' (aka 'long')" error message in the return line. Also I have a warning in the NSLog line: "Format specifies type 'long' but the argument has type 'NSString *'". How do I fix it?


Solution

  • Shouldn't you use something like this instead?

    [persons sortUsingComparator:
        ^NSComparisonResult(id obj1, id obj2) {
            Person *p1 = (Person*)obj1;
            Person *p2 = (Person*)obj2;
    
            if (p1.personAge > p2.personAge) {
                return (NSComparisonResult)NSOrderedDescending;
            }
    
            if (p1.personAge < p2.personAge) {
                return (NSComparisonResult)NSOrderedAscending;
            }
    
            return (NSComparisonResult)NSOrderedSame;
        }
    ];
    

    The thing is that you have rely on the compare method which doesn't exist on NSInteger: it is only a typedef of int. So you want to compare integer value instead and returns an NSComparisonResult value to denote the ordering of your object accordingly.