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?
The trick to sorting an array is a method on the array itself called "sortedArrayUsingDescriptors:". The method takes an array of NSSortDescriptor objects. These descriptors allow you to describe how your data should be sorted.
NSArray and its subclass NSMutableArray manage ordered collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArray .
The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .
shouldn't u 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.
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