Reputation: 65
i tried this, this and this link
I have an array (Say personObjectArray) which contains objects of class Person.
Class Person having 2 variables say,
NSString *name, NSString *age
.
Here age has type of nsstring.
Now when i sort like below,
personObjectArray = [[personObjectArray sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){
return [p1.age compare:p2.age];
}] mutableCopy];
It sorts like this,
1, 11, 123 2, 23, 3... It sorts like alphabetical order not considering it as an number.
So i change my code like this,
personObjectArray = [[personObjectArray sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){
return [[p1.age intValue] compare:[p2.age intValue] ];
}] mutableCopy];
And it says, Bad receiver type 'int'
How can i sort now ? Please don't tell me to change the datatype of age in Person class. I can't change it. Any help appreciated (: , Thanks for the time.
Upvotes: 2
Views: 111
Reputation: 1919
You were using compare on a primitive (Not Object) type int
, hence it won't work.
Try this
return [@([p1.age intValue]) compare:@([p2.age intValue])];
Here, we are using NSNumber (Which is an object type) to compare the int values
@() is a NSNumber's literal
Hope this will help you.. (:
Upvotes: 2
Reputation: 80
Try this :
personObjectArray = [[personObjectArray sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){
return [p1.age compare:p2.age options:NSNumericSearch];
}] mutableCopy];
Upvotes: 0