user1595462
user1595462

Reputation: 155

How to sort a NSMutableArray with custom object?

i have a mutable array with objects "XX" and i want to sort the array according to the variables contained in the object "XX" (see below the structure of the object).

I want to sort the array ascending by VALUE1,VALUE2 and then by NAME.

Is there any way to do it?

@interface XX:NSObject{

float VALUE1;
float VALUE2
NSString* NAME;

}

@end interface

Any help , very much appreciated!!! :-) Thank you!

Upvotes: 1

Views: 37

Answers (1)

CBredlow
CBredlow

Reputation: 2840

What you need to use is something called a Comparator block. This can be used to sort your array when you do

array sortUsingComparator: ^(id objA, id obj2){
   if(((XX*)objA).Value1 > ((XX*)obj2).Value1){
        return (NSComparisonResult)NSOrderedDescending;
   }else if(((XX*)objA).Value1 < ((XX*)obj2).Value1){
        return (NSComparisionResult)NSOrderedAscending;
   }else{
      //keep comparing here, because value 1 are equal
   }
   //sorting logic goes here, returning a (NSComparisonResult) type here
}];

Upvotes: 1

Related Questions